jQuery 封裝了三種最常用的 AJAX 簡寫方法:$.get、$.post、$.getJSON。本文詳細對比三者差異、適用場景、參數用法、跨域機制(JSONP),並提供實戰程式碼範例與避坑指南。
| 方法 | HTTP Method | 資料傳遞 | 回傳資料類型 | 跨域支援 | 適用場景 |
|---|---|---|---|---|---|
$.get | GET | Query String | 自動判斷 (xml, json, script, text, html) | 否 (同源策略) | 單純查詢、冪等操作、SEO 友善 |
$.post | POST | Request Body (form/data) | 自動判斷 | 否 (同源策略) | 提交表單、修改資料、非冪等操作 |
$.getJSON | GET | Query String + callback 參數 | 強制 JSON | 是 (JSONP) | 跨域讀取公開 API、CDN 資料 |
$.get('/api/users', {
page: 1,
limit: 20,
keyword: 'john'
}, function (data, textStatus, jqXHR) {
// data: 解析後的物件/陣列 (視 Content-Type)
// textStatus: 'success' / 'error' / 'notmodified' ...
// jqXHR: 包裝後的 XMLHttpRequest
console.log('用戶列表:', data);
renderUserTable(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
console.error('請求失敗:', textStatus, errorThrown);
});
$.post('/api/users', {
username: 'john_doe',
email: 'john@example.com',
role: 'admin'
}, function (res, textStatus, jqXHR) {
if (res.success) {
alert('建立成功,ID: ' + res.data.id);
} else {
alert('失敗: ' + res.message);
}
}, 'json') // 明確指定期望回傳 JSON,避免自動判斷失誤
.fail(function (jqXHR) {
if (jqXHR.status === 422) {
var errors = jqXHR.responseJSON.errors;
showValidationErrors(errors);
}
});
// 跨域 API 必須支援 JSONP (回呼函式名稱參數通常為 callback/jsonpCallback)
$.getJSON('https://api.example.com/v1/public-data?callback=?', {
category: 'news',
limit: 10
}, function (data) {
// 成功回調,data 為解析後的 JSON 物件
console.log('跨域資料:', data);
}).fail(function (jqXHR, textStatus, errorThrown) {
console.error('JSONP 請求失敗:', textStatus, errorThrown);
// 注意:JSONP 失敗無法獲取 HTTP 狀態碼,errorThrown 通常為 'Error: jQuery... timeout'
});
jQuery123456789,註冊為全域函式。callback=jQuery123456789。jQuery123456789({...JSON...})(JavaScript 執行語句)。限制:僅支援 GET、無法獲取 HTTP 狀態碼/Headers、需後端配合輸出函式呼叫格式、有 XSS 風險(只信任可信域名)。
// 全域 AJAX 事件 (jQuery 1.8+ 推薦用 .ajaxSetup 或攔截器)
$.ajaxSetup({
// 統一加入 CSRF Token
beforeSend: function (xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name=csrf-token]').attr('content'));
},
// 統一錯誤提示
error: function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status === 401) {
location.href = '/login?redirect=' + encodeURIComponent(location.pathname);
} else if (jqXHR.status === 403) {
alert('權限不足');
} else {
console.error('AJAX 錯誤:', textStatus, errorThrown);
}
}
});
// Fetch (原生、Promise-based)
fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'John' })
}).then(r => r.json()).then(data => console.log(data));
// Axios (功能豐富、攔截器、TypeScript 友善)
axios.post('/api/users', { name: 'John' })
.then(res => console.log(res.data))
.catch(err => console.error(err.response?.data || err.message));
建議:新專案優先使用 Axios 或原生 Fetch,jQuery AJAX 適用於維護舊專案或輕量頁面不想引入額外依賴的情況。
$.post 預設 application/x-www-form-urlencoded,送 JSON 需 contentType: 'application/json' + JSON.stringify(需用 $.ajax)。cache: false 或時間戳參數。Access-Control-Allow-Origin),JSONP 為 legacy 方案。abort() 或取消訂閱。熟練掌握三大方法差異與現代替代方案,讓資料交互開發更得心應手。