Home > Web Front-end > JS Tutorial > body text

How to Sequence AJAX Requests Iteratively

Barbara Streisand
Release: 2024-10-20 12:35:30
Original
298 people have browsed it

How to Sequence AJAX Requests Iteratively

Sequencing AJAX Requests

In various scenarios, developers may encounter the need to iterate through a collection, initiating an AJAX request for each element. The objective is to allow each request to complete before proceeding to the next element, steering clear of overwhelming the server with concurrent requests and potential issues. Moreover, avoiding the use of synchronous AJAX calls ensures that the browser remains responsive.

Design Pattern for Iterating Through Collections

While a common solution involves creating an iterator context that advances upon each successful callback, many seek a more streamlined approach. Here are a few effective design patterns:

jQuery 1.5

The jQuery 1.5 version of the solution utilizes the $.Deferred, $.queue(), and $.ajax() methods. It also provides a promise that resolves upon request completion.

<code class="javascript">$.ajaxQueue = function(ajaxOpts) {
  var jqXHR, dfd = $.Deferred(), promise = dfd.promise();

  ajaxQueue.queue(doRequest);

  promise.abort = function(statusText) {
    if (jqXHR) {
      return jqXHR.abort(statusText);
    }
    var queue = ajaxQueue.queue(), index = $.inArray(doRequest, queue);
    if (index > -1) {
      queue.splice(index, 1);
    }
    dfd.rejectWith(ajaxOpts.context || ajaxOpts,
      [promise, statusText, ""]);
    return promise;
  };

  function doRequest(next) {
    jqXHR = $.ajax(ajaxOpts)
      .done(dfd.resolve)
      .fail(dfd.reject)
      .then(next, next);
  }

  return promise;
};</code>
Copy after login

jQuery 1.4

For earlier versions of jQuery (1.4 specifically), leveraging the animation queue on an empty object provides a means to create a custom "queue" for AJAX requests.

<code class="javascript">(function($) {
  var ajaxQueue = $({});

  $.ajaxQueue = function(ajaxOpts) {
    var oldComplete = ajaxOpts.complete;

    ajaxQueue.queue(function(next) {
      ajaxOpts.complete = function() {
        if (oldComplete) oldComplete.apply(this, arguments);
        next();
      };

      $.ajax(ajaxOpts);
    });
  };
})(jQuery);</code>
Copy after login

Example Usage

Consider the following HTML structure:

<code class="html"><ul id="items">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

<ul id="output"></ul></code>
Copy after login

Using the $.ajaxQueue() plugin, you can copy the HTML of the items in #items to #output:

<code class="javascript">$("#items li").each(function(idx) {
  $.ajaxQueue({
    url: '/echo/html/',
    data: {html : "["+idx+"] "+$(this).html()},
    type: 'POST',
    success: function(data) {
      $("#output").append($("<li>", { html: data }));
    }
  });
});</code>
Copy after login

This approach ensures that the copy requests are handled sequentially, preventing any potential issues arising from excessive server load.

The above is the detailed content of How to Sequence AJAX Requests Iteratively. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!