如何获取jQuery Ajax的状态码

10

我想知道如何在jQuery中获取ajax状态码。

我有这个ajax块:

$.ajax{
    type: "GET",
    url: "keyword_mapping.html",
    data:"ajax=yes&sf="+status_flag,

    success: callback.success,
    complete: rollup_filters(),
    failure: function(){
        alert("Failure");
    }
    }

现在在上面的代码中,如果失败了,我该如何获取ajax状态码和该状态码的一些描述信息?


1
请查看文档 - Felix Kling
4个回答

11
你想使用error选项来捕获这个。例如:
error: function (jqXHR, textStatus, errorThrown)
    // Your handler here...
}

然后,您可以使用 jqXHR 对象来检索有关失败的信息。

根据文档

为了与 XMLHttpRequest 向后兼容,jqXHR 对象将公开以下属性和方法:

  • readyState
  • status
  • statusText
  • responseXML 和/或 responseText(当底层请求分别响应 xml 和/或文本时)
  • setRequestHeader(name, value)(与标准不同,它将旧值替换为新值而不是将新值连接到旧值)
  • getAllResponseHeaders()
  • getResponseHeader()
  • abort()

3
首先,您有一些语法错误。上面是一个方法调用,因此需要遵循$.ajax({ ... });(带括号)。
其次,您想将failure属性作为对象的一部分提供,而不是error(请参见文档了解更多信息)。
第三,在绑定错误时,会提供三个参数:jqHXR、textState和errorThrow。这些参数将向您提供失败的AJAX调用的详细信息(更具体地说,请尝试jqXHR.status)。
或者,您也可以绑定到$.ajaxError函数。
更新 为了使其更加现代化,您现在应该遵循Deferred API(自jQuery 1.5以来),这将使绑定到错误看起来像以下内容:
$.ajax({ /* options */ })
  .done(function( data, textStatus, jqXHR ){
    // here you bind to a successful execution.
  .fail(function( jqXHR, textStatus, errorThrown ){
    // Here you can catch if something went wrong with the AJAX call.
  })
  .always(function(){
    // here you can execute code after both (or either) of
    // the above callbacks have executed.
  });

2

将您的失败回调函数更改为

error:function (xhr, options, error){
    alert(xhr.status);
    alert(error);
}

1

在ajax设置中,没有像failure这样的东西。将failure替换为error,您将在错误回调中获得3个参数。第一个参数是xhr对象,其中包含一个状态属性。

$.ajax{
    type: "GET",
    url: "keyword_mapping.html",
    data:"ajax=yes&sf="+status_flag,

    success: callback.success;
    complete: rollup_filters(),
    error: function(jqXHR, textStatus, errorThrown){
         alert(jqXHR.status);
    }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接