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

后端 未结 4 1182
伪装坚强ぢ
伪装坚强ぢ 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 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.
        }
    } 
    

提交回复
热议问题