【问题标题】:How do I get the HTTP status code with jQuery?如何使用 jQuery 获取 HTTP 状态码?
【发布时间】:2011-02-26 17:02:18
【问题描述】:

我想检查一个页面是否返回状态码 401。这可能吗?

这是我的尝试,但它只返回 0。

$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    complete: function(xhr, statusText){
    alert(xhr.status); 
    }
});

【问题讨论】:

  • 检查statusText的值,而不是回调函数的第二个参数。
  • 这会提醒“需要授权”。我可以使用它,但 401 警报会更好;)

标签: jquery ajax xmlhttprequest http-status-codes http-status-code-401


【解决方案1】:

这可以通过 jQuery $.ajax() 方法实现

$.ajax(serverUrl, {
   type: OutageViewModel.Id() == 0 ? "POST" : "PUT",
   data: dataToSave,
   statusCode: {
      200: function (response) {
         alert('1');
         AfterSavedAll();
      },
      201: function (response) {
         alert('1');
         AfterSavedAll();
      },
      400: function (response) {
         alert('1');
         bootbox.alert('<span style="color:Red;">Error While Saving Outage Entry Please Check</span>', function () { });
      },
      404: function (response) {
         alert('1');
         bootbox.alert('<span style="color:Red;">Error While Saving Outage Entry Please Check</span>', function () { });
      }
   }, success: function () {
      alert('1');
   },
});

【讨论】:

  • 所以把 400 改成 401。
  • @StuckBetweenTrees 有什么关系?
  • 注意code 200(done) 参数是data 而其他(fail) 是jqXHR
【解决方案2】:

第三个参数是 XMLHttpRequest 对象,所以你可以为所欲为。

$.ajax({
  url  : 'http://example.com',
  type : 'post',
  data : 'a=b'
}).done(function(data, statusText, xhr){
  var status = xhr.status;                //200
  var head = xhr.getAllResponseHeaders(); //Detail header info
});

【讨论】:

  • 它返回:XMLHttpRequest cannot load example.com。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'stackoverflow.com'。
  • 您必须启用 CORS 处理才能摆脱“Access-Control-Allow-Origin”问题。根据您处理的项目类型,您可能无法简单地解决此问题,特别是如果 API 位于不同的域中并且不允许跨域请求
  • @Annjawn 如何处理 CORS,就好像我使用 Php 进行相同的 API 调用一样,它不会给出任何 CORS 错误,但如果我是同一个 API 调用的 ajax,我会给出 CORS 错误。请告诉我
  • 如果状态码是 400(可能其他不是 200 的代码),这将不起作用
【解决方案3】:

使用错误回调。

例如:

jQuery.ajax({'url': '/this_is_not_found', data: {}, error: function(xhr, status) {
    alert(xhr.status); }
});

会提示 404

【讨论】:

  • 确实如此。我对 jQuery 有点陌生。但是 401 状态呢?如何将状态保存到变量? o_O
  • 它会以同样的方式显示 401。你到底想对错误做什么?
  • 如果 401 不将用户发送到此页面。该错误仅在找不到页面时发出警报 (404)
  • 在 Firefox 中进行了测试,它也捕获了 401,也许并非所有浏览器都如此
【解决方案4】:

我觉得你也应该实现$.ajax方法的错误功能。

错误(XMLHttpRequest,文本状态, errorThrown)函数

请求时调用的函数 失败。函数通过三个 参数: XMLHttpRequest 对象, 描述错误类型的字符串 发生的和可选的 异常对象,如果发生。 第二个可能的值 参数(除了 null)是“超时”, “错误”、“未修改”和 “解析器错误”。

$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    complete: function(xhr, statusText){
        alert(xhr.status); 
    },
    error: function(xhr, statusText, err){
        alert("Error:" + xhr.status); 
    }
});

【讨论】:

  • thx,但是完成只返回0。是否可以得到401码?
  • 服务器返回 HTTP 401(未授权)时,您确定调用了 complete 吗?我还没有测试过,但我预计会调用该错误。
  • complete 类型:Function(jqXHR jqXHR, String textStatus) 请求完成时调用的函数(在执行成功和错误回调之后)。该函数获得两个参数:jqXHR(在 jQuery 1.4.x 中,XMLHTTPRequest)对象和一个对请求状态进行分类的字符串(“成功”、“未修改”、“错误”、“超时”、“中止”或“解析器错误”)。从 jQuery 1.5 开始,完整的设置可以接受一个函数数组。每个函数都会被依次调用。这是一个 Ajax 事件。
【解决方案5】:

我找到了这个解决方案,您可以简单地, 使用状态码检查服务器响应码。

示例:

$.ajax({
type : "POST",
url : "/package/callApi/createUser",
data : JSON.stringify(data),
contentType: "application/json; charset=UTF-8",
success: function (response) {  
    alert("Account created");
},
statusCode: {
    403: function() {
       // Only if your server returns a 403 status code can it come in this block. :-)
        alert("Username already exist");
    }
},
error: function (e) {
    alert("Server error - " + e);
} 
});

【讨论】:

  • 如果响应不成功且响应状态码甚至不是 403 则进入错误块。
【解决方案6】:
$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    error: function(xhr, statusText, errorThrown){alert(xhr.status);}
});

【讨论】:

    【解决方案7】:

    我将 jQuery Ajax 封装到一个方法中:

    var http_util = function (type, url, params, success_handler, error_handler, base_url) {
    
        if(base_url) {
            url = base_url + url;
        }
    
        var success = arguments[3]?arguments[3]:function(){};
        var error = arguments[4]?arguments[4]:function(){};
    
    
    
        $.ajax({
            type: type,
            url: url,
            dataType: 'json',
            data: params,
            success: function (data, textStatus, xhr) {
    
                if(textStatus === 'success'){
                    success(xhr.code, data);   // there returns the status code
                }
            },
            error: function (xhr, error_text, statusText) {
    
                error(xhr.code, xhr);  // there returns the status code
            }
        })
    
    }
    

    用法:

    http_util('get', 'http://localhost:8000/user/list/', null, function (status_code, data) {
        console(status_code, data)
    }, function(status_code, err){
        console(status_code, err)
    })
    

    【讨论】:

      【解决方案8】:

      我在使用 ajax + jQuery v3 从 JSON API 获取响应状态代码和数据时遇到了重大问题。 jQuery.ajax 仅在状态为成功的情况下解码 JSON 数据,并且它还会根据状态代码交换回调参数的顺序。呜呜呜。

      解决此问题的最佳方法是调用.always 链方法并进行一些清理。这是我的代码。

      $.ajax({
              ...
          }).always(function(data, textStatus, xhr) {
              var responseCode = null;
              if (textStatus === "error") {
                  // data variable is actually xhr
                  responseCode = data.status;
                  if (data.responseText) {
                      try {
                          data = JSON.parse(data.responseText);
                      } catch (e) {
                          // Ignore
                      }
                  }
              } else {
                  responseCode = xhr.status;
              }
      
              console.log("Response code", responseCode);
              console.log("JSON Data", data);
          });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-12
        • 2019-04-06
        • 2023-04-02
        • 1970-01-01
        • 1970-01-01
        • 2011-10-05
        • 2014-10-17
        • 2019-07-22
        相关资源
        最近更新 更多