Best way to check if AJAX request was successful in jQuery

前端 未结 3 1403
挽巷
挽巷 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.

提交回复
热议问题