Solutions to prevent duplicate sending of Ajax requests

Time:2020-10-24

There are multiple buttons in the page. Click this button to read data from the server asynchronously, and then display the data in the front end. Each button click requests the same page, but the parameters of the request are different, so the content returned is different. Multiple asynchronous requests are issued when multiple buttons are continuously clicked. The data will be displayed in turn according to the return speed of the request (because the parameters of different buttons are different and the return contents are different, there will be a button to click first. Because the amount of data requested is relatively large, the data will be displayed later.

1、 Problem solving

There are two ways to solve this problem

  • 1. When multiple requests are made in succession and the URL address of the requests is the same. Discard all previous requests and execute only the last request.
  • 2. When multiple requests are made in succession and the URL address of the requests is the same. Discard all subsequent requests and execute only the first request.

2、 Solutions

1. Set async of the Ajax request to false


$.ajax({ 
 async: false, 
 type : "POST", 
 url : defaultPostData.url, 
 dataType : 'json', 
 success : function(data) { 

 } 
}); 

async

  • Type: Boolean
  • Default value: true. By default, all requests are asynchronous. If you need to send a synchronization request, set this option to false.
  • Note that the synchronization request will lock the browser, and the user must wait for the request to complete before performing other operations.

2. Interrupt request using jQuery ajaxprefilter

Because the first plan is only a way to save the country in a curve, it can not really solve the above problems. Therefore, it is recommended to use this method.

var pendingRequests = {};
 $.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
  var key = options.url;
  console.log(key);
  if (!pendingRequests[key]) {
   pendingRequests[key] = jqXHR;
  }else{
   // jqXHR.abort (); // commit triggered after abandonment
   Pendingrequests [key]. Abort(); // abort the first triggered submission
  }

  var complete = options.complete;
  options.complete = function(jqXHR, textStatus) {
   pendingRequests[key] = null;
   if ($.isFunction(complete)) {
   complete.apply(this, arguments);
   }
  };
 });

Prefilters are prefilters that are sent before each request and processed before they are processed by $. Ajax().

  • Options is the requested option
  • The originaloptions value is provided as an unmodified option for Ajax methods, so there is no default value in the ajaxsettings settings
  • Jqxhr is the requested jqxhr object

The core idea of the above is to maintain a queue. When sending a request, the request is added to the queue. After the request is responded, it is cleared from the queue. This ensures that only one same request can be sent at any time

limitations:Only the foreground prevents jQuery from Ajax requests. For non jQuery Ajax requests, it does not work. Because the Ajax prefilter function of jQuery is used, it only works on the Ajax request of jQuery.

After calling abort, jQuery will execute the error method and throw the exception information of abort. You can distinguish this type of exception in the following ways.

var ajax = $.ajax({
 'error':function(jqXHR, textStatus, errorThrown){
  if(errorThrown != 'abort'){
   //Methods executed after AJAX is called abort
   Alert ('your Ajax method has been stopped ');
  }
 }
})

3、 Demo

Each click of the button will send a request to the back end. The demo below ensures that the request for the last click is successful after clicking the button several times.

<button>button1</button>
<button>button2</button>
<button>button3</button>  
<script>
  var pendingRequests = {};
  jQuery.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
   var key = options.url;
   console.log(key);
   if (!pendingRequests[key]) {
    pendingRequests[key] = jqXHR;
   }else{
    // jqXHR.abort (); // commit triggered after abandonment
    Pendingrequests [key]. Abort(); // abort the first triggered submission
   }

   var complete = options.complete;
   options.complete = function(jqXHR, textStatus) {
    pendingRequests[key] = null;
    if (jQuery.isFunction(complete)) {
    complete.apply(this, arguments);
    }
   };
  });
  <! -- start loading application list asynchronously -- >

  $("#button1").live("click", function() {
    $.ajax('config/ajax/appinfoListFetcher.json', {
    type:'POST',
    data: {param1:value1,
       param2:value2,
      },
    success: function(res){
      //Back end data is written back to the page
    },
    error:function(jqXHR, textStatus, errorThrown){
     if(errorThrown != 'abort'){
      //Methods executed after AJAX is called abort
      Alert ('application loading failed! ).
     }
    }
    });
    <! -- end of asynchronous loading application list -- >
   });
</script>

The above is to solve the problem of sending Ajax requests repeatedly. I hope it is helpful to our study.