测序Ajax请求 [英] Sequencing ajax requests

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

问题描述

我发现我有时需要遍历一些集合,然后Ajax调用每个元素。我想每次调用移动到下一个元素,这样我就不会爆炸的服务器请求之前返回 - 这往往会导致其他问题。我不希望异步设置为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?

推荐答案

我开发了一个 $。ajaxQueue() 插件,使用 $。递延 .queue() 和的 $阿贾克斯() 也传回的promise 的请求完成时得到解决。

jQuery 1.5+

I developed an $.ajaxQueue() plugin that uses the $.Deferred, .queue(), and $.ajax() to also pass back a promise that is resolved when the request completes.

/*
* 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.

您甚至可以考虑此因素到自己的 $。阿贾克斯()更换。这个插件 $。ajaxQueue()使用标准的FX队列的jQuery,这将自动启动首次添加的元素,如果队列中没有运行。

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 =项目> 有一些<李> 我们想要的(使用AJAX!)复制到< UL ID =输出>

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天全站免登陆