Javascript 如何在jQueryPost中获取HTTP错误响应代码

Javascript 如何在jQueryPost中获取HTTP错误响应代码,javascript,jquery,jquery-mobile,jquery-post,Javascript,Jquery,Jquery Mobile,Jquery Post,我有一个包装器函数用于向服务器发送请求,如果服务器返回401代码,我需要做一些特定的事情,但我不确定如何获取这些数据 $.mobile.showPageLoadingMsg(); $.post(apiUrl+method,p,function(d) { $.mobile.hidePageLoadingMsg(); console.log(d.success); console.log(d.message); if(d.success == tru

我有一个包装器函数用于向服务器发送请求,如果服务器返回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()承诺并获得如下状态代码:

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

请注意,从jQuery 3.0开始.error()承诺就被删除了

==not==,就像wise for!==!=:)