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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5344145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 10:58:27  来源:igfitidea点击:

How to get response status code from jQuery.ajax?

ajaxjquery-1.5

提问by Mahesh

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.ajax 调用中获取 HTTP 响应代码。然后,如果代码是 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”响应标头。我在“完成”的最后一行设置了断点。

Thanks much.

非常感谢。

回答by Adam Ayres

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);
    } 
});

回答by face

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 websitehere:

跨越这个古老的线程搜索来抓类似的解决方案我和发现接受的答案使用是.complete()的方法jquery ajax。我在这里引用jquery 网站上的通知:

The jqXHR.success(), jqXHR.error(), and jqXHR.complete()callbacks are deprecatedas 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 codeof a ajax response, one can use the following code:

要了解status codeajax 响应,可以使用以下代码:

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

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

类似地适用于.done().fail()

回答by Livingston Samuel

When your XHR request returns a Redirect response (HTTP Status 301, 302, 303, 307), the XMLHttpRequestautomatically 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 statusproperty of the xhr object.

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

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

所以你不能从响应头重定向的位置301302303307请求。

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.

您可能需要更改服务器逻辑,以可以处理重定向的方式进行响应,而不是让浏览器执行此操作。一个示例实现

回答by rstackhouse

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

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

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

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

但是,正如利文斯顿塞缪尔所说,不可能在 javascript 中捕获 301 状态代码。

回答by Przemys?aw Sienkiewicz

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

您可以检查您的响应内容,只需 console.log 即可,您将看到哪个属性具有状态代码。不懂jsons请参考视频:https: //www.youtube.com/watch?v=Bv_5Zv5c-Ts

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

回答by Naftali aka Neal

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.x 中,XMLHTTPRequest)对象和对请求状态进行分类的字符串(“成功”、“未修改”、“错误”、“超时”、“中止”或“解析器错误”) .

see: jQuery ajax

参见: jQuery ajax

so you would do:

所以你会这样做:

jqxhr.statusto get the status

jqxhr.status获取状态

回答by SurfingSanta

NB: Using jQuery 3.4.1

注意:使用 jQuery 3.4.1

$.ajax({
  url: URL,
  success: function(data, textStatus, jqXHR){
    console.log(textStatus + ": " + jqXHR.status);
    // do something with data
  },
  error: function(jqXHR, textStatus, errorThrown){
    console.log(textStatus + ": " + jqXHR.status + " " + errorThrown);
  }
});