How do I get HTTP error response code in Jquery POST

风流意气都作罢 提交于 2019-12-08 20:28:33

问题


I have a wrapper function used to send requests to a server, I need to do something specific if the server returns a code of 401 and I'm not sure how to get this data

 $.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");
});

If my server side code throws a 401 exception the jquery .error function picks this up just because its not 200 OK but I need to check if its a 401 code.


回答1:


In the error callback, check xhr.status where xhr is the first argument to the function.




回答2:


Update on the "promise" method: as of jQuery 1.5 we can call the .fail() promise and get the status code like this:

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

Note that .error() promise is removed as of jQuery 3.0



来源:https://stackoverflow.com/questions/8513295/how-do-i-get-http-error-response-code-in-jquery-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!