核心配置選項速查表
| 參數 | 類型 | 默認值 | 說明 |
| url | String | 當前頁 | 請求地址 |
| type/method | String | 'GET' | 'GET'/'POST'/'PUT'/'DELETE' 等 |
| data | Object/String | - | 發送數據,對象自動序列化 |
| dataType | String | 智能判斷 | xml/html/script/json/jsonp/text |
| async | Boolean | true | true=異步,false=同步(阻塞 UI) |
| timeout | Number | 0(無超時) | 超時毫秒數,覆蓋全局設置 |
| cache | Boolean | true* | false 禁用緩存(*script 默認 false) |
| contentType | String | application/x-www-form-urlencoded | 請求頭 Content-Type |
| processData | Boolean | true | false 禁止自動序列化(如發送 FormData) |
| beforeSend | Function | - | 發送前修改 XHR,return false 取消 |
| success | Function | - | 成功回調 (data, textStatus, jqXHR) |
| error | Function | - | 失敗回調 (jqXHR, textStatus, errorThrown) |
| complete | Function | - | 完成回調(成功失敗皆調用) |
| headers | Object | - | 額外請求頭 {key: value} |
| xhrFields | Object | - | 設置 XHR 屬性,如 withCredentials: true |
| crossDomain | Boolean | 自動檢測 | 強制跨域模式 |
| jsonp | String | 'callback' | JSONP 回調參數名 |
| jsonpCallback | String/Function | 自動生成 | 指定 JSONP 回調函數名 |
實戰示例:標準 RESTful 交互
$.ajax({
url: '/api/users',
type: 'POST',
data: JSON.stringify({name: '張三', age: 25}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
headers: {
'Authorization': 'Bearer ' + getToken(),
'X-Request-ID': generateId()
},
timeout: 10000,
beforeSend: function(xhr) {
showLoading();
// 可修改 xhr 或 return false 取消
},
success: function(data, textStatus, jqXHR) {
hideLoading();
if (data.code === 0) {
renderUserList(data.data);
showToast('創建成功');
} else {
showError(data.msg);
}
},
error: function(jqXHR, textStatus, errorThrown) {
hideLoading();
var msg = '請求失敗';
if (textStatus === 'timeout') msg = '請求超時';
else if (jqXHR.status === 401) msg = '未授權,請重新登錄';
else if (jqXHR.status >= 500) msg = '服務器錯誤';
showError(msg);
},
complete: function() {
// 總是執行:關閉 loading、恢復按鈕狀態等
resetFormState();
}
});
全局事件與 $.ajaxSetup()
// 全局默認設置
$.ajaxSetup({
cache: false, // 禁用 GET 緩存
dataType: 'json', // 默認期望 JSON
timeout: 15000, // 15 秒超時
xhrFields: {
withCredentials: true // 攜帶 Cookie 跨域
}
});
// 全局事件(所有 ajax 觸發)
$(document).ajaxStart(function() { showGlobalLoading(); });
$(document).ajaxStop(function() { hideGlobalLoading(); });
$(document).ajaxError(function(e, jqXHR, settings, err) {
logError(settings.url, err);
});
FormData 文件上傳(processData: false)
var formData = new FormData();
formData.append('file', $('#fileInput')[0].files[0]);
formData.append('folder', 'avatars');
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
processData: false, // 必須 false,否則會嘗試序列化 FormData
contentType: false, // 必須 false,讓瀏覽器自動設置 boundary
success: function(res) { /* ... */ }
});
JSONP 跨域示例
$.ajax({
url: 'https://api.example.com/data',
dataType: 'jsonp',
jsonp: 'callback', // 參數名 callback=?
jsonpCallback: 'myCallback', // 固定回調名(可選)
success: function(data) { console.log(data); }
});
// 產生請求:.../data?callback=myCallback&_=timestamp
Promise 化用法 (jQuery 3+)
// 返回 Promise,支持 then/catch/finally
$.ajax({url: '/api/data'})
.then(function(data) { return process(data); })
.then(function(processed) { render(processed); })
.catch(function(jqXHR, status, err) { handleError(err); })
.finally(function() { hideLoading(); });
// 並發請求
$.when(
$.ajax('/api/users'),
$.ajax('/api/posts'),
$.ajax('/api/comments')
).done(function(usersRes, postsRes, commentsRes) {
// 每個參數是 [data, textStatus, jqXHR]
initDashboard(usersRes[0], postsRes[0], commentsRes[0]);
});
常見坑點避雷
- ❌
async: false 同步請求會凍結瀏覽器,嚴禁生產使用
- ❌
data: {arr: [1,2]} 會序列化為 arr[]=1&arr[]=2,PHP 需 $_GET['arr'] 獲取數組
- ✅ 統一錯誤處理放在
ajaxError 全局事件
- ✅ 文件上傳必須
processData: false, contentType: false
- ✅ 跨域攜帶 Cookie 需
xhrFields: {withCredentials: true} + 服務端 Access-Control-Allow-Credentials: true