排序ajax请求 [英] Sequencing ajax requests

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

问题描述

我发现我有时需要迭代一些集合,并为每个元素做一个ajax调用。我希望每次调用返回,然后再移动到下一个元素,这样我就不会用服务器发出请求,这往往会导致其他问题。而且我不想将异步设置为false并冻结浏览器。



通常这涉及到设置某种迭代器上下文,通过每个成功回调。我认为必须有一个更简单的方法?



有没有人有一个聪明的设计模式,如何整齐地通过一个集合为每个项目做ajax调用?

解决方案

jQuery 1.5 +



我开发了一个 $。ajaxQueue() 插件,使用< a href =http://api.jquery.com/category/deferred-object/ =noreferrer> $。延期 .queue() ,而 $。ajax() 还传回一个 promise

  / * 
* jQuery.ajaxQueue - ajax请求的队列
*
*(c)2011 Corey Frang
*麻省理工学院和GPL许可证。
*
*需要jQuery 1.5+
* /
(function($){

// jQuery on a empty object,we'll going to使用它作为我们的队列
var ajaxQueue = $({});

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

//排队我们的ajax请求
ajaxQueue.queue(doRequest);

/ / add中止方法
promise.abort = function(statusText){

//代理中止到jqXHR,如果它是活动的
if(jqXHR){
return jqXHR.abort(statusText);
}

//如果还没有一个jqXHR,我们需要从队列中删除
var queue = ajaxQueue.queue()
index = $ .inArray(doRequest,queue);

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

//然后拒绝延期的
dfd.rejectWith( ajaxOpts.context || ajaxOpts,
[promise,statusText,]);

退货承诺;
};

//运行实际查询
函数doRequest(next){
jqXHR = $ .ajax(ajaxOpts)
.done(dfd.resolve)
.fail(dfd.reject)
.then(next,next);
}

退货承诺;
};

})(jQuery);



jQuery 1.4



如果你使用jQuery 1.4,您可以使用空对象上的动画队列为您的元素的ajax请求创建自己的队列。



您甚至可以将这一点纳入您自己的 $。ajax()替换。这个插件 $。ajaxQueue()为jQuery使用标准的'fx'队列,如果队列尚未运行,它将自动启动第一个添加的元素。 ($($){
// jQuery在空对象上,我们将使用这个作为我们的队列
var ajaxQueue = $({});

$ .ajaxQueue = function(ajaxOpts){
//保存原始完整功能
var oldComplete = ajaxOpts.complete ;

//排队我们的ajax请求
ajaxQueue.queue(function(next){

//创建一个完整的回调来触发队列中的下一个事件
ajaxOpts.complete = function(){
//如果是
,则触发原始的完成if(oldComplete)oldComplete.apply(this,arguments);

next(); //运行队列中的下一个查询
};

//运行查询
$ .ajax(ajaxOpts);
}) ;
};

})(jQuery);



使用示例



所以,一个< ul id =items> 其中有一些我们要复制的< li> 使用ajax!)到< ul id =output>

  //获取每个我们要复制的项目
$(#items li)。each(function(idx){

//排队ajax请求
$ .ajaxQueue({
url:'/ echo / html /',
data:{html:[+ idx +]+ $(this).html()},
type:'POST',
success:function(data){
//写入#output
$(#output)。append($(< li> ,{html:data}));
}
});
});

jsfiddle演示 - 1.4版本


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?

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

解决方案

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

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.

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);

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 demonstration - 1.4 version

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

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