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

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

如果我的服务器端代码抛出一个401exception,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