Didn"t forge 2011-03-17 19:25 采纳率: 25%
浏览 740

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

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>

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

Thanks much.

转载于:https://stackoverflow.com/questions/5344145/how-to-get-response-status-code-from-jquery-ajax

  • 写回答

6条回答 默认 最新

  • perhaps? 2011-03-17 19:30
    关注

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

报告相同问题?

悬赏问题

  • ¥15 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流