Solution to prevent repeated sending of Ajax requests, ajax requests

Source: Internet
Author: User

Solution to prevent repeated sending of Ajax requests, ajax requests

There are multiple buttons on the page. Click this button to asynchronously read data from the server, and then display the data on the front end. The page for each button clicking request is the same, but the request parameters are different, so the returned content is different. Multiple asynchronous requests are sent when multiple buttons are clicked consecutively. Then, based on the speed returned by the request (because different button parameters have different returned content, there will be different speed points), the data will be displayed in sequence, then a button clicked first will appear, due to the large amount of data requested by him, the data is displayed later.

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. Discard all previous requests and only execute the last request.
  • 2. When multiple requests are made consecutively and the requested url address is the same. Discard all subsequent requests and only execute the first request.

Ii. 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 requests. To send a synchronization request, set this option to false.
  • Note: The synchronous request locks the browser. Other operations can be performed only after the request is completed.

2. Interrupt the request using jquery ajaxPrefilter

Because the first solution is just a way to save the country, the above problem cannot be solved. Therefore, we recommend that you 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 (); // submit pendingRequests [key] triggered after giving up. abort (); // discard the first-triggered commit} 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 before each request and processed by $. ajax.

  • Options is the request option.
  • The originalOptions value is an option that is provided to the Ajax method without modification. Therefore, there is no default value in the ajaxSettings settings.
  • JqXHR is the requested jqXHR object.

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

Limitations:Only the front-end prevents ajax requests from jquery. It does not work for non-jquery ajax requests. Because jquery's ajaxPreFilter function is used, it only serves jquery's ajax requests.

After calling abort, jquery will execute the error method and throw the exception information of abort. You can use the following methods to differentiate exceptions of this type.

Var ajax = $. ajax ({'error': function (jqXHR, textStatus, errorThrown) {if (errorThrown! = 'Abort ') {// method alert executed after ajax is called abort ('your ajax method has been stopped ');}}})

Iii. Demo

Each time you click a button, a request is sent to the backend. After you click the button multiple times in the demo below, you can only ensure that the last request is 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 (); // submit pendingRequests [key] triggered after giving up. abort (); // discard the first-triggered commit} var complete = options. complete; options. complete = function (jqXHR, textStatus) {pendingRequests [key] = null; if (jQuery. isFunction (complete) {complete. apply (this, arguments) ;}};}); <! -- Load 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 is written back to the page }, error: function (jqXHR, textStatus, errorThrown) {if (errorThrown! = 'Abort ') {// method alert executed after ajax is called abort ('application loading failed! ') ;}}}); <! -- End of Asynchronously loading the Application List -- >}); </script>

The above is a solution to repeatedly sending Ajax requests, hoping to help you learn.

Articles you may be interested in:
  • Various solutions for multiple ajax requests (synchronization, queue, and cancel requests)
  • Notes for asynchronous and synchronous Ajax requests
  • Analysis of ajax request json data and js parsing (Example Analysis)
  • How to cyclically output the Json format data returned by an ajax request to a table
  • How to implement an ajax request every five minutes in Javascript
  • Simple Example of JQuery Ajax request to implement partial refresh
  • How can I solve the timeout of Ajax requests when the data volume is large?
  • Example of jquery cross-origin request sharing (jquery sends ajax requests)
  • Examples of how to use the when in jQuery to implement multiple AJAX requests corresponding to a single callback

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.