Ajax error
函數中的必需參數是jqXHR, exception
,您可以像下面這樣使用它:
$.ajax({
url: 'some_unknown_page.html',
success: function (response) {
$('#post').html(response.responseText);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$('#post').html(msg);
},});
DEMO FIDDLE
參數
jqXHR:
它實際上是一個看起來像這樣的錯誤對象
您還可以在自己的瀏覽器控制臺中查看此內容,方法是使用console.log
以下error
函數:
error: function (jqXHR, exception) {
console.log(jqXHR);
// Your error handling logic here..}
我們使用status
此對象的屬性來獲取錯誤代碼,就像我們獲得status = 404一樣,這意味著找不到請求的頁面。它根本不存在?;谠摖顟B代碼,我們可以將用戶重定向到登錄頁面或我們的業務邏輯需要的任何內容。
例外:
這是字符串變量,顯示異常類型。因此,如果我們收到404錯誤,則exception
文本只是“錯誤”。同樣,我們可能會將'超時','中止'作為其他異常文本。
取消通知:該jqXHR.success()
,jqXHR.error()
和jqXHR.complete()
回調棄用的jQuery 1.8。要準備的代碼為他們的最終消除,使用jqXHR.done()
,jqXHR.fail()
和jqXHR.always()
來代替。
因此,如果您使用的是jQuery 1.8或更高版本,我們需要更新成功和錯誤函數邏輯,如: -
// Assign handlers immediately after making the request,// and remember the jqXHR object for this requestvar jqxhr = $.ajax("some_unknown_page.html")
.done(function (response) {
// success logic here
$('#post').html(response.responseText);
})
.fail(function (jqXHR, exception) {
// Our error logic here
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$('#post').html(msg);
})
.always(function () {
alert("complete");
});
希望能幫助到你!