How to use status codes 200, 404, 300 (how jquery is executed and does not work inside)

I learned Ajax using jQuery. I think jQuery implements the use of status codes, but does not know much about status codes such as 200, 404 and 300.

With jQuery Ajax its simple:

$.ajax({
    url: "update.php",
    type: "POST",
    data: customObj
})
.done(function( data ) {
    alert("data saved succesfully");
})
.fail(function( data ) {
    alert( "failed to update data" );
});

Can someone explain how to use these status codes 200, 404 and 300.

+4
source share
3 answers

In addition to what @dfsq wrote , you can handle certain status codes:

$.ajax({
  statusCode: {
    404: function() {
      alert( "page not found" );
    }
  }
});

or with a delay:

$.ajax({
    url: "update.php",
    type: "POST",
    data: customObj
})
.fail(function( jqXHR, textStatus, errorThrown) {
    if (jqXHR.status == 403) {
        alert( "forbidden" );
    }
});

or

$.ajax({
    url: "update.php",
    type: "POST",
})
.statusCode({
    401: function() { alert( 'Unauthorized' ); },
    200: function() { alert( 'OK!'); }
});
+6
source

If you look at $. ajax implementation, you will find these lines of code:

// Callback for when everything is done
function done(status, nativeStatusText, responses, headers) {

    ...

    // Determine if successful
    isSuccess = status >= 200 && status < 300 || status === 304;

    ...

    // Success/Error
    if (isSuccess) {
        deferred.resolveWith(callbackContext, [success, statusText, jqXHR]);
    } else {
        deferred.rejectWith(callbackContext, [jqXHR, statusText, error]);
    }

    ...
}

, , 200-300 304 , - . , (done, success ) (fail) .

+7

Source: https://habr.com/ru/post/1526754/


All Articles