如何使用jQuery获取HTTP状态代码?

hor*_*gen 66 ajax jquery xmlhttprequest http-status-codes http-status-code-401

我想检查页面是否返回状态代码401.这可能吗?

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

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

Rav*_*tal 91

这可以使用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');
   },
});
Run Code Online (Sandbox Code Playgroud)

  • 所以将400更改为401. (24认同)

b12*_*400 61

第三个参数是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
});
Run Code Online (Sandbox Code Playgroud)

  • 如果状态代码为 400(可能对于其他不是 200 的代码),这将不起作用 (3认同)

bal*_*loo 20

使用错误回调.

例如:

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

将提醒404


GvS*_*GvS 8

我认为你还应该实现$ .ajax方法的错误功能.

错误(XMLHttpRequest,textStatus,errorThrown)函数

请求失败时要调用的函数.该函数传递三个参数:XMLHttpRequest对象,描述发生的错误类型的字符串和可选的异常对象(如果发生).第二个参数的可能值(除了null)是"timeout","error","notmodified"和"parsererror".

$.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); 
    }
});
Run Code Online (Sandbox Code Playgroud)

  • thx,但完成只返回0.是否可以获得401代码? (3认同)

Jig*_*edi 7

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

示例:

$.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);
} 
});
Run Code Online (Sandbox Code Playgroud)

  • 如果响应不成功且响应状态代码甚至不是 403,则它会进入错误块。 (2认同)

var*_*tec 6

$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    error: function(xhr, statusText, errorThrown){alert(xhr.status);}
});
Run Code Online (Sandbox Code Playgroud)