[英]How do I get HTTP error response code in Jquery POST
我有一個用於向服務器發送請求的包裝函數,如果服務器返回401的代碼,我需要做一些特定的事情,我不知道如何獲取這些數據
$.mobile.showPageLoadingMsg();
$.post(apiUrl+method,p,function(d) {
$.mobile.hidePageLoadingMsg();
console.log(d.success);
console.log(d.message);
if(d.success == true){
window[callback](d.data);
}
else{
if(d.message != null){
alert(d.message);
}
}
},'json')
.error(function() {
//need to check for 401 status here to do something
$.mobile.hidePageLoadingMsg();
alert("error");
});
如果我的服務器端代碼拋出一個401異常,jquery .error函數選擇它只是因為它不是200 OK但是我需要檢查它是否是401代碼。
在error
回調中,檢查xhr.status
,其中xhr
是函數的第一個參數。
更新“promise”方法:從jQuery 1.5開始,我們可以調用.fail()promise並獲取如下狀態代碼:
$.post( "example.php", function() {
alert( "success" );
}).fail(function(xhr) {
console.log(xhr.status);
});
請注意,自jQuery 3.0起,刪除了.error()promise
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.