首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

jQuery $.ajax 替代 $.getJSON:錯誤處理與完整控制優勢

     編輯:更多程式設計知識

$.getJSON() 是 $.ajax() 的簡寫,但**無法捕捉網路層錯誤**(如 404、500、斷網),導致使用者無感知。使用完整 $.ajax() 並設定 dataType: 'json' 可獲得 error 回調,實現健壯的錯誤處理。

對比代碼

// $.getJSON:無 error 回調,網路錯誤靜默失敗
$.getJSON(destUrl, function(data) {
  if (data) linfo.innerHTML = data;
  loadimg.style.display = 'none';
});

// $.ajax 完整版:捕捉網路與 HTTP 錯誤
$.ajax({
  type: 'GET',
  url: destUrl,
  dataType: 'json',
  success: function(data) {
    if (data) linfo.innerHTML = data;
    loadimg.style.display = 'none';
  },
  error: function(xhr, status, error) {
    alert('非同步查詢出錯:' + error);
    loadimg.style.display = 'none';
  }
});

error 回調參數詳解

  • xhr:jqXHR 物件,含 status、statusText、responseText 等屬性。
  • status:錯誤類型字串:"timeout", "error", "abort", "parsererror"。
  • error:HTTP 狀態文字(如 "Not Found", "Internal Server Error")。

進階錯誤處理策略

error: function(xhr, status, error) {
  var msg = '請求失敗';
  if (status === 'timeout') msg = '請求超時,請重試';
  else if (status === 'parsererror') msg = '資料格式錯誤';
  else if (xhr.status === 404) msg = '介面不存在 (404)';
  else if (xhr.status >= 500) msg = '伺服器內部錯誤 (' + xhr.status + ')';
  else msg += ':' + error;
  console.error(msg, xhr);
  showUserFriendlyToast(msg);
}

何時仍可用 $.getJSON

  • 極簡原型開發、內部工具、確定網路可靠且不需錯誤提示場景。
  • 正式產品**強烈建議**使用 $.ajax 完整配置。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved