如何从 jQuery.ajax 获取响应状态代码? [英] How to get response status code from jQuery.ajax?

查看:53
本文介绍了如何从 jQuery.ajax 获取响应状态代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中,我所做的只是从 jQuery.ajax 调用中获取 HTTP 响应代码.然后,如果代码是 301(永久移动),则显示位置"响应头:

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:

<?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>

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

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'.

非常感谢.

推荐答案

我看到 jqXhr 对象上的状态字段,这里是一个摆弄它的工作:

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

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

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

这篇关于如何从 jQuery.ajax 获取响应状态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆