$.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';
}
});
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);
}
$.ajax 完整配置。