萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

為什麼 $.ajax() 比 $.getJSON() 更強大?錯誤處理機制深度解析

核心差異

$.getJSON() 是 $.ajax() 的簡易封裝,預設 dataType: 'json'、method: 'GET',**缺乏 error 回調參數**。一旦網路異常、伺服器回傳非 2xx、或 JSON 解析失敗,getJSON 會靜默失敗,開發者完全無感知。

程式碼對比

$.getJSON(無法捕捉錯誤)

$.getJSON('/api/data', function(data) {
  console.log('成功', data);
});
// 網路斷線、500 錯誤、回傳非 JSON 時:這裡完全不會執行,也沒有任何錯誤訊息

$.ajax(完整錯誤處理)

$.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();
  }
});

error 回調參數詳解

參數型別說明
jqXHRjqXHR ObjectjQuery 封裝的 XMLHttpRequest,擴充 status、responseText、responseJSON、getResponseHeader() 等
textStatusString"timeout"、"error"、"abort"、"parsererror"(JSON 解析失敗)
errorThrownStringHTTP 狀態文字,如 "Not Found"、"Internal Server Error"

何時必須用 $.ajax()?

  1. 需要區分 網路錯誤 vs 業務邏輯錯誤(如 400/401/403/404/500)。
  2. 需實作 請求超時 處理(timeout: 5000)。
  3. 需在 complete 統一清理狀態(Loading、按鈕解鎖)。
  4. 需自訂 Request Header(如 Authorization: Bearer xxx)。
  5. 需支援 POST/PUT/DELETE 或 FormData 上傳。
  6. 需 取消請求(儲存 jqXHR 物件呼叫 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(),建立完善的錯誤邊界與使用者體驗。

copyright © 萬盛學電腦網 all rights reserved