对ajax请求进行排序 [英] Sequencing ajax requests

查看:36
本文介绍了对ajax请求进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现有时需要迭代一些集合并对每个元素进行 ajax 调用.我希望每次调用都在移动到下一个元素之前返回,这样我就不会向服务器发送请求 - 这通常会导致其他问题.而且我不想将 async 设置为 false 并冻结浏览器.

I find I sometimes need to iterate some collection and make an ajax call for each element. I want each call to return before moving to the next element so that I don't blast the server with requests - which often leads to other issues. And I don't want to set async to false and freeze the browser.

通常这涉及设置某种迭代器上下文,我在每次成功回调时都会通过这些迭代器上下文.我认为一定有更简洁的方法吗?

Usually this involves setting up some kind of iterator context that i step thru upon each success callback. I think there must be a cleaner simpler way?

有没有人有一个巧妙的设计模式,如何巧妙地处理一个集合,为每个项目进行 ajax 调用?

Does anyone have a clever design pattern for how to neatly work thru a collection making ajax calls for each item?

推荐答案

jQuery 1.5+

我开发了一个 $.ajaxQueue() 使用 $.Deferred 的插件,.queue()$.ajax() 也传回 promise 在请求完成时解析.

/*
* jQuery.ajaxQueue - A queue for ajax requests
* 
* (c) 2011 Corey Frang
* Dual licensed under the MIT and GPL licenses.
*
* Requires jQuery 1.5+
*/ 
(function($) {

// jQuery on an empty object, we are going to use this as our Queue
var ajaxQueue = $({});

$.ajaxQueue = function( ajaxOpts ) {
    var jqXHR,
        dfd = $.Deferred(),
        promise = dfd.promise();

    // queue our ajax request
    ajaxQueue.queue( doRequest );

    // add the abort method
    promise.abort = function( statusText ) {

        // proxy abort to the jqXHR if it is active
        if ( jqXHR ) {
            return jqXHR.abort( statusText );
        }

        // if there wasn't already a jqXHR we need to remove from queue
        var queue = ajaxQueue.queue(),
            index = $.inArray( doRequest, queue );

        if ( index > -1 ) {
            queue.splice( index, 1 );
        }

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

        return promise;
    };

    // run the actual query
    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 请求创建您自己的队列".

jQuery 1.4

If you're using jQuery 1.4, you can utilize the animation queue on an empty object to create your own "queue" for your ajax requests for the elements.

您甚至可以将其考虑到您自己的 $.ajax() 替换中.这个插件 $.ajaxQueue() 使用 jQuery 的标准fx"队列,如果队列尚未运行,它将自动启动第一个添加的元素.

You can even factor this into your own $.ajax() replacement. This plugin $.ajaxQueue() uses the standard 'fx' queue for jQuery, which will auto-start the first added element if the queue isn't already running.

(function($) {
  // jQuery on an empty object, we are going to use this as our Queue
  var ajaxQueue = $({});

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

    // queue our ajax request
    ajaxQueue.queue(function(next) {

      // create a complete callback to fire the next event in the queue
      ajaxOpts.complete = function() {
        // fire the original complete if it was there
        if (oldComplete) oldComplete.apply(this, arguments);

        next(); // run the next query in the queue
      };

      // run the query
      $.ajax(ajaxOpts);
    });
  };

})(jQuery);

示例用法

因此,我们有一个 <ul id="items">,其中有一些

  • 我们想要复制(使用 ajax!)

      Example Usage

      So, we have a <ul id="items"> which has some <li> that we want to copy (using ajax!) to the <ul id="output">

      // get each item we want to copy
      $("#items li").each(function(idx) {
      
          // queue up an ajax request
          $.ajaxQueue({
              url: '/echo/html/',
              data: {html : "["+idx+"] "+$(this).html()},
              type: 'POST',
              success: function(data) {
                  // Write to #output
                  $("#output").append($("<li>", { html: data }));
              }
          });
      });
      

      jsfiddle 演示 - 1.4 版本

      这篇关于对ajax请求进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆