$.getJSON() 是 $.ajax() 的簡易封裝,預設 dataType: 'json'、method: 'GET',**缺乏 error 回調參數**。一旦網路異常、伺服器回傳非 2xx、或 JSON 解析失敗,getJSON 會靜默失敗,開發者完全無感知。
$.getJSON('/api/data', function(data) {
console.log('成功', data);
});
// 網路斷線、500 錯誤、回傳非 JSON 時:這裡完全不會執行,也沒有任何錯誤訊息
$.ajax({
url: '/api/data',
type: 'GET',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
console.log('成功', data);
},
error: function(jqXHR, textStatus, errorThrown) {
// jqXHR: 包含 status, statusText, responseText, getAllResponseHeaders()
// textStatus: 'timeout', 'error', 'abort', 'parsererror'
// errorThrown: HTTP 狀態文字 (如 'Not Found', 'Internal Server Error')
console.error('請求失敗:', textStatus, errorThrown);
if (jqXHR.status === 0) {
alert('網路不通或跨域被攔截');
} else if (jqXHR.status === 401) {
location.href = '/login'; // 未授權導向登入
} else if (jqXHR.status >= 500) {
alert('伺服器內部錯誤,請稍後再試');
} else {
alert('請求異常:' + jqXHR.statusText);
}
},
complete: function(jqXHR, textStatus) {
// 成功/失敗皆執行:關閉 Loading、釋放按鈕鎖定等
hideLoading();
}
});
| 參數 | 型別 | 說明 |
|---|---|---|
| jqXHR | jqXHR Object | jQuery 封裝的 XMLHttpRequest,擴充 status、responseText、responseJSON、getResponseHeader() 等 |
| textStatus | String | "timeout"、"error"、"abort"、"parsererror"(JSON 解析失敗) |
| errorThrown | String | HTTP 狀態文字,如 "Not Found"、"Internal Server Error" |
timeout: 5000)。Authorization: Bearer xxx)。abort())。// utils/request.js
export function request(url, options = {}) {
return $.ajax({
url,
type: options.method || 'GET',
data: options.params,
dataType: 'json',
contentType: options.contentType || 'application/json',
headers: options.headers,
timeout: 10000,
beforeSend: xhr => {
const token = localStorage.getItem('token');
if (token) xhr.setRequestHeader('Authorization', 'Bearer ' + token);
}
}).then(
res => res, // 成功直接回傳資料
(jqXHR, textStatus) => {
// 統一錯誤轉換為 Promise rejection
const err = new Error(textStatus);
err.status = jqXHR.status;
err.response = jqXHR.responseJSON;
throw err;
}
);
}
$.getJSON() 適合快速原型、無需錯誤處理的唯讀資料;正式專案請直接使用 $.ajax() 或封裝後的 request(),建立完善的錯誤邊界與使用者體驗。