如何在Jquery POST中获得HTTP错误响应代码?

How do I get HTTP error response code in Jquery POST

本文关键字:错误 HTTP 响应 代码 Jquery POST      更新时间:2023-09-26

我有一个用于向服务器发送请求的包装器函数,如果服务器返回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);
});

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