jQuery: How to get the HTTP status code from within the $.ajax.error method?

后端 未结 4 1181
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 16:44

I\'m using jQuery to make an AJAX request. I want to perform different actions whether or not the HTTP status code is a 400 error or a 500 error. How can I achieve this?

相关标签:
4条回答
  • 2020-12-02 16:54

    If you're using jQuery 1.5, then statusCode will work.

    If you're using jQuery 1.4, try this:

    error: function(jqXHR, textStatus, errorThrown) {
        alert(jqXHR.status);
        alert(textStatus);
        alert(errorThrown);
    }
    

    You should see the status code from the first alert.

    0 讨论(0)
  • 2020-12-02 17:01

    You should create a map of actions using the statusCode setting:

    $.ajax({
      statusCode: {
        400: function() {
          alert('400 status code! user error');
        },
        500: function() {
          alert('500 status code! server error');
        }
      }
    });
    

    Reference (Scroll to: 'statusCode')

    EDIT (In response to comments)

    If you need to take action based on the data returned in the response body (which seems odd to me), you will need to use error: instead of statusCode:

    error:function (xhr, ajaxOptions, thrownError){
        switch (xhr.status) {
            case 404:
                 // Take action, referencing xhr.responseText as needed.
        }
    } 
    
    0 讨论(0)
  • 2020-12-02 17:11

    use

       statusCode: {
        404: function() {
          alert('page not found');
        }
      }
    

    -

    $.ajax({
        type: 'POST',
        url: '/controller/action',
        data: $form.serialize(),
        success: function(data){
            alert('horray! 200 status code!');
        },
        statusCode: {
        404: function() {
          alert('page not found');
        },
    
        400: function() {
           alert('bad request');
       }
      }
    
    });
    
    0 讨论(0)
  • 2020-12-02 17:12

    An other solution is to use the response.status function. This will give you the http status wich is returned by the ajax call.

    function checkHttpStatus(url) {     
        $.ajax({
            type: "GET",
            data: {},
            url: url,
            error: function(response) {
                alert(url + " returns a " + response.status);
            }, success() {
                alert(url + " Good link");
            }
        });
    }
    
    0 讨论(0)
提交回复
热议问题