How do I get the HTTP status code with jQuery?

前端 未结 9 1471
逝去的感伤
逝去的感伤 2020-11-27 13:34

I want to check if a page returns the status code 401. Is this possible?

Here is my try, but it only returns 0.

$.ajax({
    url: \"http://my-ip/tes         


        
相关标签:
9条回答
  • 2020-11-27 14:24

    I found this solution where you can simply, check the server response code using status code.

    Example :

    $.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);
    } 
    });
    
    0 讨论(0)
  • 2020-11-27 14:31

    I think you should also implement the error function of the $.ajax method.

    error(XMLHttpRequest, textStatus, errorThrown)Function

    A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "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); 
        }
    });
    
    0 讨论(0)
  • 2020-11-27 14:37

    The third argument is the XMLHttpRequest object, so you can do whatever you want.

    $.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
    });
    
    0 讨论(0)
提交回复
热议问题