How to cancel an $.ajax request if a previous is r

2020-07-27 02:45发布

问题:

I have this simple piece of code:

$(document).on("input", "#addFoodSearch", function(event){
   var search = $(this).val();
   $.ajax({ url: "/ajax/search-food.php", type: 'GET', data: { 'search' : search }, dataType: 'json' }).done(
      function(data){
         if (data[0] == 'success'){
            $('#add-food-area').html(data[1]);
            $('#add-food-area').fadeIn();
         }
      }
   );
});

What I want to do is to cancel a previous $.ajax request, if any is running, in case the user types too fast. I need only the latest request to pass, not the whole sequence of them.

How can I do this?

回答1:

Store the jqXHR object in a variable and abort it each time.

var jqxhr = {abort: function () {}};
$(document).on("input", "#addFoodSearch", function(event){
    var search = $(this).val();
    jqxhr.abort();
    jqxhr = $.ajax(...


回答2:

You'd need to store a reference to the AJAX request in progress, then call the abort() method on it;

var ajax;

$(document).on("input", "#addFoodSearch", function(event){
   var search = $(this).val();

   if (ajax) {
       ajax.abort();
   }

   ajax = $.ajax({ url: "/ajax/search-food.php", type: 'GET', data: { 'search' : search }, dataType: 'json' }).done(
      function(data){
         if (data[0] == 'success'){
            $('#add-food-area').html(data[1]);
            $('#add-food-area').fadeIn();
         }
      }
   ).always(function () {
       ajax = undefined;
   });
});

... although note that cancelling an AJAX request doesn't always prevent the request from being completed on the server.