【问题标题】:jQuery: How to get the HTTP status code from within the $.ajax.error method?jQuery:如何从 $.ajax.error 方法中获取 HTTP 状态代码?
【发布时间】:2011-10-05 18:16:40
【问题描述】:

我正在使用 jQuery 发出 AJAX 请求。无论 HTTP 状态代码是 400 错误还是 500 错误,我都想执行不同的操作。我怎样才能做到这一点?

$.ajax({
    type: 'POST',
    url: '/controller/action',
    data: $form.serialize(),
    success: function(data){
        alert('horray! 200 status code!');
    },
    error: function(data){
        //get the status code
        if (code == 400) {
            alert('400 status code! user error');
        }
        if (code == 500) {
            alert('500 status code! server error');
        }
    },
});

更新:

@GeorgeCummins 提到使用响应正文“似乎很奇怪”。这是我第一次尝试做这种事情。我的方法不是最佳实践吗?你会推荐什么?我在这里为此创建了另一个 StackOverflow 问题:What response/status code should I send to an AJAX request when there is a user/form validation error?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    您应该使用statusCode 设置创建一个动作映射:

    $.ajax({
      statusCode: {
        400: function() {
          alert('400 status code! user error');
        },
        500: function() {
          alert('500 status code! server error');
        }
      }
    });
    

    Reference(滚动到:'statusCode')

    EDIT(回应 cmets)

    如果您需要根据响应正文中返回的数据采取措施(我觉得这很奇怪),您需要使用 error: 而不是 statusCode:

    error:function (xhr, ajaxOptions, thrownError){
        switch (xhr.status) {
            case 404:
                 // Take action, referencing xhr.responseText as needed.
        }
    } 
    

    【讨论】:

    • 我从那条路线开始,但不知道如何获取数据。您如何访问响应正文?
    • @Andrew:为什么需要访问响应正文?您是否希望在发生 400 或 500 错误时返回有用的数据?
    • 是的,我使用状态码 400 来处理表单验证错误。 (不确定这是否合适)
    • 在这种情况下,您能否在400: function() { 的正文中采取适当的表单验证操作。只需删除 alert() 并添加必要的代码。
    • 为什么告诉 API 调用者确切的问题是什么而不是告诉他们 400 很奇怪。
    【解决方案2】:

    使用

       statusCode: {
        404: function() {
          alert('page not found');
        }
      }
    

    -

    $.ajax({
        type: 'POST',
        url: '/controller/action',
        data: $form.serialize(),
        success: function(data){
            alert('horray! 200 status code!');
        },
        statusCode: {
        404: function() {
          alert('page not found');
        },
    
        400: function() {
           alert('bad request');
       }
      }
    
    });
    

    【讨论】:

    • 如何捕捉意外的 statusCode,这个版本的语法中是否有 catch-all 或 else 处理程序?
    【解决方案3】:

    如果您使用的是 jQuery 1.5,那么 statusCode 可以工作。

    如果你使用的是 jQuery 1.4,试试这个:

    error: function(jqXHR, textStatus, errorThrown) {
        alert(jqXHR.status);
        alert(textStatus);
        alert(errorThrown);
    }
    

    您应该会看到第一个警报的状态代码。

    【讨论】:

    • 哦,我明白了我的问题。我在想data 被传递给错误方法,但实际上是jqXHRtextStatuserrorThrown
    • 我喜欢你的回答,因为你提到了不同版本的 jQuery 之间的差异,我一开始并没有注意到。
    • 我在 jQ 2.x 中使用您的示例,状态始终为零 (0),textStatus 始终为“错误”,错误抛出为空。有任何想法吗?我做了什么:页面加载后关闭服务器以弄清楚发生了什么。
    • 当我得到状态码 419 时它对我有用,我可以处理错误。
    【解决方案4】:

    另一种解决方案是使用 response.status 函数。这将为您提供 ajax 调用返回的 http 状态。

    function checkHttpStatus(url) {     
        $.ajax({
            type: "GET",
            data: {},
            url: url,
            error: function(response) {
                alert(url + " returns a " + response.status);
            }, success() {
                alert(url + " Good link");
            }
        });
    }
    

    【讨论】:

    • 这个解决方案最好
    【解决方案5】:

    在这里你也可以使用它,它对我有用

    $.ajax({
      success: function(data, textStatus, xhr) {
        console.log(xhr.status);
      },
      complete: function(xhr, textStatus) {
        console.log(xhr.status);
      } 
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-17
      • 2011-02-26
      • 2010-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多