2011-12-14 90 views
7

我有一個用於向服務器發送請求的包裝函數,如果服務器返回401代碼,並且我不確定如何獲取這個數據如何在JQuery POST中獲取HTTP錯誤響應代碼

$.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行,但我需要檢查,如果它是一個401碼。

+0

===不== ==,就像明智的!==!= :) – Sam 2014-10-13 10:00:50

回答

11

error回調中,檢查xhr.status其中xhr是該函數的第一個參數。

0

更新的「承諾」的方法: 在jQuery 1.5,我們可以調用.fail()承諾,獲得狀態代碼:

$.post("example.php", function() { 
    alert("success"); 
}).fail(function(xhr) { 
    console.log(xhr.status); 
}); 

注意.error()承諾是去除截至jQuery 3.0

相關問題