$.ajax({
url: '/api/users', // 必填
type: 'POST', // GET/POST/PUT/DELETE...
data: { id: 1, name: 'Tom' }, // 對象/字符串/FormData
dataType: 'json', // 預期返回類型:json/xml/html/script/text/jsonp
contentType: 'application/x-www-form-urlencoded; charset=UTF-8', // 發送編碼
processData: true, // 是否將 data 轉為查詢字符串(FormData 設 false)
async: true, // true=異步,false=同步(阻塞瀏覽器,慎用)
timeout: 10000, // 超時毫秒數
cache: false, // GET 請求是否緩存
headers: { 'X-CSRF-Token': '...' }, // 自定義請求頭
xhrFields: { withCredentials: true }, // 跨域攜帶 Cookie
beforeSend: function(xhr) { // 請求前:可修改 xhr、返回 false 取消
showLoading();
},
success: function(data, textStatus, xhr) { // 成功回調
render(data);
},
error: function(xhr, textStatus, errorThrown) { // 失敗回調
handleError(xhr, status, error);
},
complete: function(xhr, textStatus) { // 完成回調(成功/失敗都執行)
hideLoading();
}
});
$.post(url, data, successCallback, dataType);
// 等價於
$.ajax({ type: 'POST', url, data, success: successCallback, dataType });
同理:$.get、$.getJSON、$.getScript。
| 值 | 回調參數類型 | 備註 |
|---|---|---|
| json | Object/Array | 自動 JSON.parse,要求響應 Content-Type: application/json |
| xml | XMLDocument | 可用 jQuery 選擇器遍歷 |
| html | String | 包含 script 標簽會執行 |
| script | String | 作為 JS 執行,跨域自動轉 GET |
| text | String | 純文本 |
| jsonp | Object | 跨域 JSONP,自動處理 callback 參數 |
// 1. 純對象 -> 自動序列化為 a=1&b=2
{ a: 1, b: 2 }
// 2. 數組對象 -> a=1&a=2
{ a: [1, 2] }
// 3. 字符串 -> 直接發送(需自行編碼)
'a=1&b=2'
// 4. FormData -> multipart/form-data(文件上傳必須)
var fd = new FormData();
fd.append('file', fileInput.files[0]);
fd.append('name', 'test');
$.ajax({ data: fd, processData: false, contentType: false, ... });
// 5. 函數 -> 返回上述任意類型
data: function() { return { timestamp: Date.now() }; }
error: function(xhr, textStatus, errorThrown) {
// xhr: jqXHR 對象(包含 responseText, responseJSON, status, getResponseHeader...)
// textStatus: 'timeout' | 'error' | 'abort' | 'parsererror' | 'notmodified'
// errorThrown: HTTP 狀態文本(如 'Not Found', 'Internal Server Error')或異常對象
if (textStatus === 'timeout') { /* 超時重試 */ }
else if (textStatus === 'parsererror') { /* JSON 解析失敗 */ }
else if (xhr.status === 401) { /* 未登錄,跳轉登錄頁 */ }
else if (xhr.status === 403) { /* 無權限 */ }
else if (xhr.status >= 500) { /* 服務器錯誤 */ }
else { /* 網絡錯誤、CORS 失敗等 */ }
}
var promise = $.ajax({ url: '/api', dataType: 'json' });
promise.done(function(data) { /* success */ })
.fail(function(xhr, status, err) { /* error */ })
.always(function() { /* complete */ });
// 鏈式
$.ajax(...).then(successFn, errorFn).always(completeFn);
// 多請求並行
$.when($.ajax('/api/1'), $.ajax('/api/2')).done(function(res1, res2) {
// res1[0], res2[0] 為數據
});
application/json 頭 → parsererror。解決:後端加頭或前端 dataType: 'text' 手動 JSON.parse。xhrFields: {withCredentials:true} + 後端 Access-Control-Allow-Credentials: true + Access-Control-Allow-Origin 指定域(不可 *)。async:false 已棄用,改用 async/await + Promise。$.ajaxSetup({cache:false}) 防 GET 緩存。async function request(url, options = {}) {
const res = await fetch(url, {
method: options.method || 'GET',
headers: { 'Content-Type': 'application/json', ...options.headers },
body: options.data ? JSON.stringify(options.data) : undefined,
credentials: 'same-origin'
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return options.dataType === 'json' ? res.json() : res.text();
}
// 使用
request('/api/user', { method: 'POST', data: {id:1} }).then(render).catch(handleError);
$.ajax 是瑞士軍刀,$.post/get/getJSON 是常用刀具。掌握 dataType、data 序列化、錯誤三參數、Promise 接口、跨域憑證,即可應對 99% 場景。新項目建議漸進遷移至 Fetch + 統一攔截器,代碼更現代、可樹搖、無依賴。