如何从jQuery.ajax获取响应状态代码?

时间:2022-10-09 11:42:19

In the following code, all I am trying to do is to get the HTTP response code from a jQuery.ajax call. Then, if the code is 301 (Moved Permanently), display the 'Location' response header:

在下面的代码中,我所要做的就是从jQuery获得HTTP响应代码。ajax调用。然后,如果代码是301(永久移动),则显示“位置”响应头:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>jQuery 301 Trial</title>
  <script src="http://code.jquery.com/jquery-1.5.1.min.js"></script>

  <script type="text/javascript">
  function get_resp_status(url) {
    $.ajax({
      url: url,
      complete: function (jqxhr, txt_status) {
        console.log ("Complete: [ " + txt_status + " ] " + jqxhr);
        // if (response code is 301) {
        console.log ("Location: " + jqxhr.getResponseHeader("Location"));
        // }
      }
    });
  }
  </script>
  <script type="text/javascript">
  $(document).ready(function(){
    $('a').mouseenter(
      function () {
        get_resp_status(this.href);
      },
      function () {
      }
    );
  });
  </script>
</head>
<body>
  <a href="http://ow.ly/4etPl">Test 301 redirect</a>
  <a href="http://cnn.com/not_found">Test 404 not found</a>
</body>
</html>

Can someone point out where I am going wrong? When I check the 'jqxhr' object in Firebug, I can't find the status code, nor the 'Location' response header. I set the breakpoint on last line of 'complete'.

有人能指出我哪里出错了吗?当我在Firebug中检查“jqxhr”对象时,我找不到状态码,也找不到“Location”响应头。我在“complete”的最后一行设置断点。

Thanks much.

谢谢。

6 个解决方案

#1


164  

I see the status field on the jqXhr object, here is a fiddle with it working:

我在jqXhr对象上看到了状态字段,这里有一个对它起作用的小提琴:

http://jsfiddle.net/magicaj/55HQq/3/

http://jsfiddle.net/magicaj/55HQq/3/

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

#2


37  

When your XHR request returns a Redirect response (HTTP Status 301, 302, 303, 307), the XMLHttpRequest automatically follows the redirected URL and returns the status code of that URL.

当XHR请求返回重定向响应(HTTP状态301、302、303、307)时,XMLHttpRequest会自动跟随重定向URL并返回该URL的状态代码。

You can get the non-redirecting status codes (200, 400, 500 etc) via the status property of the xhr object.

您可以通过xhr对象的状态属性获得非重定向状态代码(200、400、500等)。

So you cannot get the redirected location from the response header of a 301, 302, 303 or 307 request.

因此,您无法从301、302、303或307请求的响应头获得重定向位置。

You might have to change your server logic to respond in a way that you can handle the redirect, rather than letting the browser do it. An example implementation.

您可能需要更改服务器逻辑,以便能够处理重定向,而不是让浏览器执行重定向。一个示例实现。

#3


35  

Came across this old thread searching for a similar solution myself and found the accepted answer to be using .complete() method of jquery ajax. I quote the notice on jquery website here:

我在这个旧的线程中搜索了一个类似的解决方案,并找到了使用jquery ajax的.complete()方法的公认答案。我在这里引用jquery网站的通知:

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

jqXHR.success()、jqXHR.error()和jqXHR.complete()回调在jQuery 1.8中被弃用。为了准备最终删除的代码,请使用jqXHR.done()、jqXHR.fail()和jqXHR.always()。

To know the status code of a ajax response, one can use the following code:

要了解ajax响应的状态代码,可以使用以下代码:

$.ajax( url [, settings ] )
.always(function (jqXHR) {
    console.log(jqXHR.status);
});

Works similarily for .done() and .fail()

与.done()和.fail()类似

#4


30  

It is probably more idiomatic jQuery to use the statusCode property of the parameter object passed to the the $.ajax function:

使用传递给$的参数对象的statusCode属性可能是更惯用的jQuery。ajax功能:

$.ajax({
  statusCode: {
    500: function(xhr) {
      if(window.console) console.log(xhr.responseText);
    }
  }
});

However, as Livingston Samuel said, it is not possible to catch 301 status codes in javascript.

然而,正如Livingston Samuel所说,用javascript捕获301状态码是不可能的。

#5


7  

You can check your respone content, just console.log it and you will see whitch property have a status code. If you do not understand jsons, please refer to the video: https://www.youtube.com/watch?v=Bv_5Zv5c-Ts

您可以检查您的respone内容,只需控制台。记录它,您将看到whitch属性有一个状态码。如果您不理解jsons,请参考视频:https://www.youtube.com/watch?

It explains very basic knowledge that let you feel more comfortable with javascript.

它解释了非常基础的知识,让您感觉更舒服的javascript。

You can do it with shorter version of ajax request, please see code above:

您可以使用更短版本的ajax请求,请参见上面的代码:

$.get("example.url.com", function(data) {
                console.log(data);
            }).done(function() {
               // TO DO ON DONE
            }).fail(function(data, textStatus, xhr) {
                 //This shows status code eg. 403
                 console.log("error", data.status);
                 //This shows status message eg. Forbidden
                 console.log("STATUS: "+xhr);
            }).always(function() {
                 //TO-DO after fail/done request.
                 console.log("ended");
            });

Example console output:

控制台输出示例:

error 403 
STATUS: Forbidden 
ended

#6


2  

jqxhr is a json object:

jqxhr是一个json对象:

complete returns:
The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror").

完整的回报:jqXHR(在jQuery 1.4中)。对象和对请求状态进行分类的字符串(“success”、“notmodified”、“error”、“timeout”、“abort”或“parsererror”)。

see: jQuery ajax

看:jQuery ajax

so you would do:

所以你会做的事:

jqxhr.status to get the status

jqxhr。获得状态的状态。

#1


164  

I see the status field on the jqXhr object, here is a fiddle with it working:

我在jqXhr对象上看到了状态字段,这里有一个对它起作用的小提琴:

http://jsfiddle.net/magicaj/55HQq/3/

http://jsfiddle.net/magicaj/55HQq/3/

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

#2


37  

When your XHR request returns a Redirect response (HTTP Status 301, 302, 303, 307), the XMLHttpRequest automatically follows the redirected URL and returns the status code of that URL.

当XHR请求返回重定向响应(HTTP状态301、302、303、307)时,XMLHttpRequest会自动跟随重定向URL并返回该URL的状态代码。

You can get the non-redirecting status codes (200, 400, 500 etc) via the status property of the xhr object.

您可以通过xhr对象的状态属性获得非重定向状态代码(200、400、500等)。

So you cannot get the redirected location from the response header of a 301, 302, 303 or 307 request.

因此,您无法从301、302、303或307请求的响应头获得重定向位置。

You might have to change your server logic to respond in a way that you can handle the redirect, rather than letting the browser do it. An example implementation.

您可能需要更改服务器逻辑,以便能够处理重定向,而不是让浏览器执行重定向。一个示例实现。

#3


35  

Came across this old thread searching for a similar solution myself and found the accepted answer to be using .complete() method of jquery ajax. I quote the notice on jquery website here:

我在这个旧的线程中搜索了一个类似的解决方案,并找到了使用jquery ajax的.complete()方法的公认答案。我在这里引用jquery网站的通知:

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

jqXHR.success()、jqXHR.error()和jqXHR.complete()回调在jQuery 1.8中被弃用。为了准备最终删除的代码,请使用jqXHR.done()、jqXHR.fail()和jqXHR.always()。

To know the status code of a ajax response, one can use the following code:

要了解ajax响应的状态代码,可以使用以下代码:

$.ajax( url [, settings ] )
.always(function (jqXHR) {
    console.log(jqXHR.status);
});

Works similarily for .done() and .fail()

与.done()和.fail()类似

#4


30  

It is probably more idiomatic jQuery to use the statusCode property of the parameter object passed to the the $.ajax function:

使用传递给$的参数对象的statusCode属性可能是更惯用的jQuery。ajax功能:

$.ajax({
  statusCode: {
    500: function(xhr) {
      if(window.console) console.log(xhr.responseText);
    }
  }
});

However, as Livingston Samuel said, it is not possible to catch 301 status codes in javascript.

然而,正如Livingston Samuel所说,用javascript捕获301状态码是不可能的。

#5


7  

You can check your respone content, just console.log it and you will see whitch property have a status code. If you do not understand jsons, please refer to the video: https://www.youtube.com/watch?v=Bv_5Zv5c-Ts

您可以检查您的respone内容,只需控制台。记录它,您将看到whitch属性有一个状态码。如果您不理解jsons,请参考视频:https://www.youtube.com/watch?

It explains very basic knowledge that let you feel more comfortable with javascript.

它解释了非常基础的知识,让您感觉更舒服的javascript。

You can do it with shorter version of ajax request, please see code above:

您可以使用更短版本的ajax请求,请参见上面的代码:

$.get("example.url.com", function(data) {
                console.log(data);
            }).done(function() {
               // TO DO ON DONE
            }).fail(function(data, textStatus, xhr) {
                 //This shows status code eg. 403
                 console.log("error", data.status);
                 //This shows status message eg. Forbidden
                 console.log("STATUS: "+xhr);
            }).always(function() {
                 //TO-DO after fail/done request.
                 console.log("ended");
            });

Example console output:

控制台输出示例:

error 403 
STATUS: Forbidden 
ended

#6


2  

jqxhr is a json object:

jqxhr是一个json对象:

complete returns:
The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror").

完整的回报:jqXHR(在jQuery 1.4中)。对象和对请求状态进行分类的字符串(“success”、“notmodified”、“error”、“timeout”、“abort”或“parsererror”)。

see: jQuery ajax

看:jQuery ajax

so you would do:

所以你会做的事:

jqxhr.status to get the status

jqxhr。获得状态的状态。