ホームページ  >  記事  >  ウェブフロントエンド  >  最適なパフォーマンスを得るために JQuery で AJAX リクエストを順次実行するにはどうすればよいですか?

最適なパフォーマンスを得るために JQuery で AJAX リクエストを順次実行するにはどうすればよいですか?

Barbara Streisand
Barbara Streisandオリジナル
2024-10-20 13:05:01837ブラウズ

How to Sequentially Execute AJAX Requests in JQuery for Optimal Performance?

AJAX リクエストを順次実行する

サーバーのパフォーマンスを維持し、ブラウザーのフリーズを回避するために、コレクションを反復処理して各要素の AJAX リクエストを順番に実行する必要があるシナリオ挑戦的になる可能性があります。この問題を解決するための革新的なアプローチは次のとおりです。

jQuery 1.5 :

Deferred、queue()、および $ を使用する $.ajaxQueue() プラグインを利用します。 .ajax() メカニズム。このプラグインは、AJAX リクエスト キューの作成を管理し、リクエストの完了時に解決される Promise を提供します。

(function($) {

  // Create an empty object as the AJAX request queue
  var ajaxQueue = $({});

  $.ajaxQueue = function(ajaxOpts) {
    // Define the deferred object and its promise
    var dfd = $.Deferred(),
        promise = dfd.promise();

    // Enqueue the AJAX request
    ajaxQueue.queue(doRequest);

    // Add an abort method to the promise
    promise.abort = function(statusText) {
      // Abort the request if active
      if (jqXHR) {
        return jqXHR.abort(statusText);
      }

      // Remove the request from the queue
      var queue = ajaxQueue.queue(),
          index = $.inArray(doRequest, queue);
      if (index > -1) {
        queue.splice(index, 1);
      }

      // Reject the deferred
      dfd.rejectWith(ajaxOpts.context || ajaxOpts,
        [promise, statusText, ""]);

      return promise;
    };

    // Define the function to execute the request
    function doRequest(next) {
      jqXHR = $.ajax(ajaxOpts)
        .done(dfd.resolve)
        .fail(dfd.reject)
        .then(next, next);
    }

    return promise;
  };

})(jQuery);

jQuery 1.4:

jQuery 1.4 を使用している場合は、空のオブジェクトのアニメーション キューを利用して、AJAX リクエスト用のカスタム "キュー" を確立できます。

(function($) {
  // Create an empty object as the AJAX request queue
  var ajaxQueue = $({});

  $.ajaxQueue = function(ajaxOpts) {
    // Hold the original complete function
    var oldComplete = ajaxOpts.complete;

    // Enqueue the AJAX request
    ajaxQueue.queue(function(next) {
      // Define a complete callback to proceed with the queue
      ajaxOpts.complete = function() {
        // Execute the original complete function, if present
        if (oldComplete) oldComplete.apply(this, arguments);

        next(); // Proceed to the next request
      };

      // Execute the request
      $.ajax(ajaxOpts);
    });
  };

})(jQuery);

使用例:

これらの手法を使用すると、次のことができます。コレクション内の各項目に対する AJAX リクエストをシーケンスし、ブラウザーのロックアップを回避しながらサーバーのパフォーマンスを確保します。

以上が最適なパフォーマンスを得るために JQuery で AJAX リクエストを順次実行するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。