使用 .ajax() 處理 HTTP 響應程式碼
除了 .done
,.fail
和 .always
承諾基於請求是否成功觸發的回撥,還可以選擇在從伺服器返回特定 HTTP 狀態程式碼時觸發函式。這可以使用 statusCode
引數完成。
$.ajax({
type: {POST or GET or PUT etc.},
url: {server.url},
data: {someData: true},
statusCode: {
404: function(responseObject, textStatus, jqXHR) {
// No content found (404)
// This code will be executed if the server returns a 404 response
},
503: function(responseObject, textStatus, errorThrown) {
// Service Unavailable (503)
// This code will be executed if the server returns a 503 response
}
}
})
.done(function(data){
alert(data);
})
.fail(function(jqXHR, textStatus){
alert('Something went wrong: ' + textStatus);
})
.always(function(jqXHR, textStatus) {
alert('Ajax request was finished')
});
正如官方 jQuery 文件所述:
如果請求成功,則狀態碼函式採用與成功回撥相同的引數; 如果它導致錯誤(包括 3xx 重定向),它們採用與
error
回撥相同的引數。