Solution _ajax related to prevent repeated sending of Ajax requests

Source: Internet
Author: User

There are multiple buttons on the page that you can click to read the data asynchronously to the server and then display the data on the front end. Each button clicks on the requested page is the same, but the requested parameters are different, so the returned content is different. Multiple asynchronous requests are made when multiple buttons are clicked continuously. Then according to the speed of the request return (because different button parameters, the return content is different, so there will be the speed of the points), the data will be displayed in turn, then there will be a first click of the button, because he requested a large amount of data, resulting in data is displayed after.

I. Problem-solving

There are two ways to solve this problem:

    • 1. When multiple requests are made consecutively, and the requested URL address is the same. Discards all previous requests and executes only the last request.
    • 2. When multiple requests are made consecutively, and the requested URL address is the same. Discards all subsequent requests and executes only the first request.

Ii. Solutions

1, the AJAX request async set to False

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

 } 
}); 

Async

    • Type: Boolean
    • Default value: True. All requests are asynchronous requests under the default settings. If you need to send a sync request, set this option to false.
    • Note that the synchronization request will lock the browser and the user's other actions must wait for the request to complete before it can be executed.

2. Use jquery Ajaxprefilter Interrupt Request

Since the first scheme is just a way of curve salvation, it really doesn't solve the problem. Therefore, it is recommended that this approach be used.

 var pendingrequests = {};
 $.ajaxprefilter (function (options, originaloptions, jqxhr) {
  var key = Options.url;
  Console.log (key);
  if (!pendingrequests[key]) {
   Pendingrequests[key] = jqxhr;
  } else{
   //jqxhr.abort ();///Discard after the triggering of the submission of
   pendingrequests[key].abort ();//Discard first triggered submission
  }

  var complete = Options.complete;
  Options.complete = function (JQXHR, textstatus) {
   Pendingrequests[key] = null;
   if ($.isfunction (complete)) {
   complete.apply (this, arguments);
   }
  };}
 );

Prefilters is a pre filter that is sent and $.ajax () to process them before each request.

    • Options is the requested option
    • Originaloptions value as an unmodified option provided to the Ajax method, so there is no default value in the Ajaxsettings setting
    • JQXHR is the requested JQXHR object

The core idea of the above is to maintain a queue, send a request, the request to join the queue, request a response, clear from the queue, which ensures that at any one time only one of the same request sent.

limitations: Just the front desk's AJAX request to prevent jquery. Ajax requests for non-jquery do not work. Because it uses the Ajaxprefilter function of jquery, it only works on jquery's AJAX requests.

After invoking Abort, jquery executes the method of error, throwing abort exception information. You can distinguish between exceptions of this type using the following methods.

var ajax = $.ajax ({
 ' error ': function (JQXHR, textstatus, Errorthrown) {
  if (errorthrown!= ' abort ') {
   // Method alert executed after Ajax was invoked abort
   (' Your Ajax method was stopped ');}}
)

Third, Demo

button Each click will send a request to the back end, the following demo implementation of multiple Click button, only to ensure that the last click of the request to be successful.

<button id= "Button1" >button1</button> <button id= "Button2" >button2</button> <button id= "
  Button3 ">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 ();///Discard after the triggering of the submission of Pendingrequests[key].abort ();//Discard first triggered submission} var complete = Options.compl
   ete;
    Options.complete = function (JQXHR, textstatus) {Pendingrequests[key] = null;
    if (jquery.isfunction (complete)) {complete.apply (this, arguments);
  }
   };
  });
    <!--start the 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 writeback to page }, Error:function (JQXHR, Textstatus, Errorthrown) {if (ERrorthrown!= ' abort ' {//ajax The method alert executed after the abort was invoked (' Application load failed!
     ');
    }
    }
    });
<!--asynchronous Load application list end-->});
 </script>

The above is the solution to repeatedly send Ajax requests, I hope to help you learn.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.