原生 XMLHttpRequest 代碼冗長、需手寫跨瀏覽器建立邏輯、狀態判斷、回調處理,團隊風格不一易生 Bug。jQuery 提供統一、鏈式、Promise 化的 AJAX API,大幅降低認知負擔,強制規範錯誤處理流程。
$.ajax(options) — 完全控制,所有高層方法最終都呼叫它。$.get(), $.post(), $.getJSON(), $.getScript() — 針對常見場景預設參數。.load() — 直接將回傳 HTML 插入元素,最適合局部刷新。// 載入純 HTML 片段並插入 #result
$("#result").load("/api/content.html");
// 攜帶參數 (自動轉 POST)
$("#result").load("/api/search", { q: "keyword", page: 1 });
// 回調函數
$("#result").load("/api/content", function(response, status, xhr) {
if (status === "error") console.error("載入失敗:", xhr.status, xhr.statusText);
});
// 篩選器:只插入回傳 HTML 中的特定片段
$("#result").load("/api/page.html #main-content .article");
限制:只能處理 HTML 回傳,無法直接處理 JSON 資料綁定。
// GET 請求
$.get("/api/users", { page: 1, limit: 20 })
.done(function(data, textStatus, jqXHR) {
renderUserList(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
handleError(jqXHR);
});
// POST 請求 (傳送 JSON 需手動序列化)
$.post("/api/users", JSON.stringify({ name: "John", age: 30 }), function(data) {
console.log("建立成功:", data);
}, "json"); // 預期回傳資料型別
$.ajax({
url: "/api/orders",
type: "POST",
dataType: "json", // 預期回傳型別: json, xml, html, script, text, jsonp
contentType: "application/json; charset=utf-8", // 發送資料型別
data: JSON.stringify({ userId: 123, status: "pending" }),
timeout: 10000, // 超時毫秒
cache: false, // GET 時加隨機參數防快取
headers: { "Authorization": "Bearer " + token }, // 自訂標頭
beforeSend: function(jqXHR, settings) {
showLoading(); // 顯示載入中
},
success: function(data, textStatus, jqXHR) {
renderOrders(data);
},
error: function(jqXHR, textStatus, errorThrown) {
if (textStatus === "timeout") showMsg("請求逾時");
else if (jqXHR.status === 401) redirectLogin();
else showMsg("伺服器錯誤: " + jqXHR.status);
},
complete: function(jqXHR, textStatus) {
hideLoading(); // 成功/失敗都會執行
}
});
所有 AJAX 方法回傳 jqXHR 物件,實作 Promise 介面:
// 鏈式錯誤處理
$.get("/api/a")
.then(function(a) { return $.get("/api/b/" + a.id); })
.then(function(b) { return $.get("/api/c/" + b.id); })
.done(function(c) { console.log("串聯完成:", c); })
.fail(function(jqXHR) { console.error("任一步驟失敗:", jqXHR.status); });
// 並行請求
$.when(
$.get("/api/users"),
$.get("/api/products"),
$.get("/api/categories")
).done(function(usersResp, productsResp, categoriesResp) {
// 每個參數都是 [data, status, jqXHR]
initPage(usersResp[0], productsResp[0], categoriesResp[0]);
});
// 全域事件 (可在 $.ajaxSetup 關閉 global: false)
$(document).ajaxStart(function() { $("#loading").show(); });
$(document).ajaxStop(function() { $("#loading").hide(); });
$(document).ajaxError(function(e, jqXHR, settings, err) { logError(settings.url, err); });
// 設定專案共用預設值
$.ajaxSetup({
cache: false,
dataType: "json",
timeout: 15000,
xhrFields: { withCredentials: true } // 跨域攜帶 Cookie
});
$("#myForm").submit(function(e) {
e.preventDefault();
var $form = $(this);
$.ajax({
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize(), // 自動序列化表單欄位
success: function(res) { if (res.ok) location.href = res.redirect; }
});
});
var formData = new FormData($("#uploadForm")[0]);
$.ajax({
url: "/api/upload",
type: "POST",
data: formData,
processData: false, // 關鍵:不要序列化 FormData
contentType: false, // 關鍵:讓瀏覽器自動設定 multipart boundary
success: function(res) { console.log(res.fileUrl); }
});
$.ajax({
url: "https://api.other.com/data",
dataType: "jsonp", // 自動處理 callback 參數
jsonp: "callback", // 參數名 (預設 callback)
jsonpCallback: "myCb", // 指定回調函數名 (可選)
success: function(data) { ... }
});
html 導致解析失敗;回傳純文字設 json 拋出 parse error。cache: false 或加時間戳。this 指向 AJAX 設定物件,非 DOM 元素,需用閉包或 $.proxy 保存參考。$.ajaxSetup({cache:false}) 並適時 abort()。統一使用 jQuery AJAX 體系,配合 Promise 模式與全域事件,能建立清晰、可維護、抗壓的非同步資料層。