Best way to check if AJAX request was successful in jQuery

前端 未结 3 1377
挽巷
挽巷 2021-01-01 21:21

I\'ve been checking to make sure my AJAX requests are successful by doing something like this:

$.post(\"page.php\", {data: stuff}, function(data, status) {
          


        
相关标签:
3条回答
  • 2021-01-01 21:32

    By calling $.post that way, you automatically pass only in a success handler function.

    If something on the request went wrong, this method is not even executed.

    To have more control either use $.ajax() directly, or pass in fail handlers. That could look like

    $.post("page.php", {data: stuff}, function(data, status) {
       // we're fine here
    }).fail(function(err, status) {
       // something went wrong, check err and status
    });
    

    The same thing using .ajax():

    $.ajax({
       type: 'POST',
       url: 'page.php',
       data: stuff,
       success: function( data ) {
       },
       error: function(xhr, status, error) {
          // check status && error
       },
       dataType: 'text'
    });
    

    You can even pass more ajax event handler to $.ajax, like beforeSend to modify/read XHR headers or complete to have a handler which fires either way (error or not) when the requests finished.

    0 讨论(0)
  • 2021-01-01 21:46

    I prefer to use the ajax call, as it has an explicit success handler

    $.ajax({
    url: "page.php",
    data: stuff,
    success: function(response){
    console.log("success");
    }
    });
    

    I'd also recommend using firebug or webkit similar, then you can track the requests and check the parameters!

    0 讨论(0)
  • 2021-01-01 21:49

    jQuery considers "successful" in the way it is in the source code, of course. This does not include a status code of 404/500 and neither a timeout, since no status code has been returned in that case.

    You can check when exactly it returns "success":

    // If successful, handle type chaining
    if ( status >= 200 && status < 300 || status === 304 ) {
    
    ...
        // If not modified
        if ( status === 304 ) {
    
            statusText = "notmodified";
    ...
    
        // If we have data
        } else {
    
            try {
    ...
                statusText = "success"; // So: only when status code is in
                                        // the range 200 <= x < 300
    ...
            } catch(e) {
    ...
                statusText = "parsererror";
    ...
            }
        }
    
    0 讨论(0)
提交回复
热议问题