| 參數 | 類型 | 默認值 | 核心作用 |
|---|---|---|---|
| url | String | 當前頁面 | 請求地址 |
| type/method | String | 'GET' | HTTP 方法 |
| data | Object/String | 無 | 發送數據,對象自動序列化 |
| dataType | String | 智能猜測 | 預期返回類型:json/xml/html/script/jsonp/text |
| contentType | String | 'application/x-www-form-urlencoded; charset=UTF-8' | 發送編碼類型 |
| timeout | Number | 0(無超時) | 請求超時毫秒數 |
| async | Boolean | true | 異步/同步(同步會阻塞瀏覽器) |
| cache | Boolean | true(GET)/false(其他) | 是否緩存 GET 請求 |
| beforeSend | Function(xhr) | 無 | 發送前修改 XHR(如設置 Header) |
| success | Function(data, status, xhr) | 無 | 成功回調 |
| error | Function(xhr, status, error) | 無 | **失敗回調,核心調試入口** |
| complete | Function(xhr, status) | 無 | 完成回調(成功/失敗都執行) |
| xhrFields | Object | 無 | 設置 XHR 屬性(如 withCredentials) |
| crossDomain | Boolean | 自動檢測 | 強制跨域模式 |
error: function(xhr, textStatus, errorThrown) {
// xhr: jqXHR 對象(XMLHttpRequest 超集)
// textStatus: 狀態字串
// errorThrown: 錯誤對象/字串
}
| 屬性/方法 | 說明 | 調試價值 |
|---|---|---|
readyState | 0=未初始化, 1=載入, 2=載入完成, 3=交互, 4=完成 | 判斷請求階段 |
status | HTTP 狀態碼:200, 404, 500, 0(網絡失敗/跨域攔截) | **最關鍵**:區分服務端錯誤/網絡錯誤/跨域 |
statusText | HTTP 狀態文本:'OK', 'Not Found', 'Internal Server Error' | 人類可讀狀態 |
responseText | 原始響應文本 | 查看服務端返回的錯誤詳情(即使非 JSON) |
responseJSON | 解析後的 JSON 對象(dataType=json 時) | 直接訪問結構化錯誤信息 |
getAllResponseHeaders() | 所有響應頭字串 | 排查 CORS、緩存、Set-Cookie |
getResponseHeader(name) | 單個響應頭 | 檢查 Content-Type、X-Custom-Header |
abort() | 中止請求 | 組件卸載時取消進行中請求 |
"timeout" // 超時
"error" // HTTP 錯誤 (4xx, 5xx) 或網絡錯誤
"abort" // 調用 abort() 主動取消
"parsererror" // 數據解析失敗 (如預期 JSON 返回 HTML)
"notmodified" // 304 Not Modified (ifModified:true 時)
statusText 字串(如 "Not Found")SyntaxError / TypeError 對象$.ajax({
url: '/api/data',
type: 'POST',
data: { id: 123 },
dataType: 'json',
timeout: 10000, // 10 秒超時
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', getCsrfToken());
showLoading();
},
success: function(data, textStatus, xhr) {
hideLoading();
if (data.code === 0) {
renderData(data.data);
} else {
showError(data.msg || '業務邏輯錯誤');
}
},
error: function(xhr, textStatus, errorThrown) {
hideLoading();
let msg = '請求失敗';
if (textStatus === 'timeout') {
msg = '請求超時,請檢查網絡';
} else if (textStatus === 'parsererror') {
msg = '服務器返回數據格式錯誤';
console.error('響應內容:', xhr.responseText); // 關鍵:看原始返回
} else if (xhr.status === 0) {
msg = '網絡異常或跨域被攔截';
} else if (xhr.status === 401) {
msg = '登錄已過期,請重新登錄';
redirectToLogin();
} else if (xhr.status === 403) {
msg = '無權限訪問';
} else if (xhr.status >= 500) {
msg = '服務器內部錯誤';
} else {
msg = `HTTP ${xhr.status}: ${xhr.statusText}`;
}
showError(msg);
// 記錄完整錯誤上下文供排查
logError({ url: this.url, data: this.data, xhr, textStatus, errorThrown });
},
complete: function(xhr, textStatus) {
// 總是執行:關閉 loading、釋放鎖、記錄日誌
console.log('請求完成:', textStatus, xhr.status);
}
});
請求失敗
├── status === 0
│ ├── 網絡斷開 / 離線
│ ├── 跨域無 CORS 標頭
│ ├── HTTPS 頁面請求 HTTP (混合內容)
│ └── 瀏覽器擴展攔截 (AdBlock 等)
├── status === 400
│ └── 參數驗證失敗 → 檢查 responseJSON.errors
├── status === 401
│ └── Token 失效 → 刷新 Token / 重定向登錄
├── status === 403
│ └── 權限不足 → 提示或隱藏功能
├── status === 404
│ └── 接口不存在 → 檢查路由/版本
├── status >= 500
│ └── 服務端異常 → 查看 responseText 錯誤堆棧
└── textStatus === 'parsererror'
├── 預期 JSON 實際返回 HTML (如錯誤頁面/登錄頁重定向)
├── JSON 格式錯誤 (尾隨逗號、未轉義字符)
└── 空響應體 → 後端返回 204/空內容
// 全局 AJAX 事件(需 global: true,默認)
$(document).ajaxError(function(event, xhr, settings, thrownError) {
console.group(`AJAX Error: ${settings.type} ${settings.url}`);
console.log('Status:', xhr.status, xhr.statusText);
console.log('Response:', xhr.responseText);
console.log('Thrown:', thrownError);
console.groupEnd();
// 統一處理 401/500 等
if (xhr.status === 401) redirectToLogin();
});
// 關閉特定請求的全局事件
$.ajax({ global: false, ... }); // 不觸發 ajaxStart/Stop/Error/Success/Complete
| 特性 | jQuery $.ajax | Fetch API |
|---|---|---|
| Promise 支援 | $.ajax().then() / .done()/.fail() | 原生 Promise |
| 超時控制 | timeout 參數 | 需 AbortController + setTimeout 手動實現 |
| 進度事件 | xhr 上綁定 progress | ReadableStream 消費 body |
| 請求取消 | xhr.abort() | AbortController.signal |
| Cookie 自動攜帶 | 同域自動 | 需 credentials: 'include' |
| JSON 自動解析 | dataType: 'json' | res.json() 手動調用 |
jQuery AJAX 調試核心口訣:
「先看
status分類錯誤類型,
再看responseText還原服務端真相,
善用beforeSend/complete管理副作用,
全局ajaxError統一攔截業務異常。」
掌握 xhr.status、textStatus、responseText 三角定位法,能解決 99% 的前後端接口對接疑難雜症。