【问题标题】:How do I get HTTP error response code in Jquery POST如何在 Jquery POST 中获取 HTTP 错误响应代码
【发布时间】:2011-12-14 23:38:45
【问题描述】:

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

【问题讨论】:

  • === 不是 ==,就像 !== != 一样明智:)

标签: javascript jquery jquery-mobile jquery-post


【解决方案1】:

error 回调中,检查xhr.status,其中xhr 是函数的第一个参数。

【讨论】:

    【解决方案2】:

    “承诺”方法的更新: 从 jQuery 1.5 开始,我们可以调用 .fail() 承诺并获得如下状态码:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      • 2013-05-23
      • 2022-01-24
      相关资源
      最近更新 更多