jQuery $.ajax() 是前端異步請求的核心 API,參數豐富且靈活。本文系統整理所有配置選項、簡寫方法、常見陷阱與現代替代方案,作為開發查閱手冊。
$.ajax(options) 完整參數表| 參數 | 類型 | 默認值 | 說明 |
|---|---|---|---|
| url | String | 當前頁面 | 請求地址 |
| type / method | String | "GET" | HTTP 方法:GET、POST、PUT、DELETE 等 |
| async | Boolean | true | true=異步,false=同步(阻塞瀏覽器,慎用) |
| timeout | Number | 0(無限制) | 請求超時毫秒數,覆蓋全局設置 |
| data | Object/String | 無 | 發送數據。Object 會用 $.param() 編碼為 key=val&...;String 直接發送 |
| processData | Boolean | true | false 時不將 data 編碼,適合發送 DOM、File、ArrayBuffer 等 |
| contentType | String | "application/x-www-form-urlencoded; charset=UTF-8" | 請求體編碼類型。發送 JSON 時需設為 "application/json" |
| dataType | String | 智能判斷 | 預期響應類型:xml、html、script、json、jsonp、text。決定回調參數類型 |
| headers | Object | {} | 額外請求頭,如 {"X-CSRF-Token": "xxx"} |
| beforeSend | Function(xhr) | 無 | 發送前修改 XHR,返回 false 可取消請求 |
| success | Function(data, textStatus, jqXHR) | 無 | 請求成功回調 |
| error | Function(jqXHR, textStatus, errorThrown) | 無 | 請求失敗回調 |
| complete | Function(jqXHR, textStatus) | 無 | 完成回調(成功/失敗均觸發) |
| cache | Boolean | true(GET 為 false) | false 時在 URL 追加 "_={timestamp}" 防緩存 |
| ifModified | Boolean | false | 僅響應 Last-Modified/ETag 變化時獲取 |
| global | Boolean | true | false 禁用全局 Ajax 事件(ajaxStart/Stop 等) |
| xhrFields | Object | {} | 設置 XHR 屬性,如 withCredentials: true 攜帶跨域 Cookie |
| crossDomain | Boolean | 自動檢測 | 強制標記為跨域請求 |
| username/password | String | 無 | HTTP 基本認證憑據 |
// GET 請求 $.get(url, data?, success?, dataType?) // POST 請求 $.post(url, data?, success?, dataType?) // 載入腳本 $.getScript(url, success?) // JSONP 跨域 $.getJSON(url, data?, success?)
$.ajax({
url: '/api/user',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({name: 'Tom', age: 20}),
dataType: 'json',
success: function(res) { console.log(res); }
});
var formData = new FormData();
formData.append('file', $('#fileInput')[0].files[0]);
formData.append('token', 'xxx');
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
processData: false, // 必須 false
contentType: false, // 必須 false,瀏覽器自動設置 boundary
success: function(res) { ... }
});
$(document).ajaxStart(function() { $('#loading').show(); });
$(document).ajaxStop(function() { $('#loading').hide(); });
$.ajaxSetup({
error: function(jqXHR, status, err) {
if (jqXHR.status === 401) location.href = '/login';
else console.error(status, err);
}
});
jqXHR.responseText 可見原始文本Access-Control-Allow-Origin$('#form').serialize() → "a=1&b=2" 字符串,適配 application/x-www-form-urlencodedJSON.stringify(),否則發送 "[object Object]"fetch(url, {method, headers, body}).then(r => r.json())axios.post(url, data)$.ajax 返回 Promise,可 await $.ajax(...)掌握 $.ajax 全參數細節,能快速定位網絡請求疑難雜症;新項目建議遷移至 Fetch 或 Axios,獲得更優雅的異步體驗。