队列AJAX调用 [英] Queue AJAX calls

查看:186
本文介绍了队列AJAX调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好我正在做一个横向滚动网站,如: http://vanityclaire.com/



然而,在加载主页之后,我使用jQuery .load()在家里的孩子们中,而不是拥有一个大的HTML文件。



目前我在每个div和ajax中都是标题中的url。但是AJAX返回乱序,并且当我添加更多页面时,不会想象 spanging 服务器有30多个http://请求。



如何同步执行AJAX调用,即等待第一个请求再转发请求,或者一次发送两个。



我一直在搜索,并且无法弄清楚我需要什么。



这是我的HTML:

 < div id =mainLayoutclass =fullwidth scrollArea> 
< div class =scrollItems>
< div id =page-1class =scrollItemtitle =/>
< div>主页内容< / div>
< / div>
< div id =page-2class =scrollItemtitle =/ Page2.html>
< div class =loading> < / DIV>
< / div>
< div id =page-3class =scrollItemtitle =/ Page3.html>
< div class =loading> < / DIV>
< / div>

< div id =page-4class =scrollItemtitle =/ Page4.html>
< div class =loading> < / DIV>
< / div>
< div id =page-5class =scrollItemtitle =/ Page5.html>
< div class =loading> < / DIV>
< / div>
< / div>
< / div>

我的JS:

  function s_loadingInitialPages(){
var loadingItems = new Array();
$(。scrollArea .scrollItem)。each(function(){
if($(this).attr('title')!='/'){
var oDelem = $(this);
loadingItems.push(oDelem);
// alert('test');
}
});

for(i = 0; i< loadingItems.length; i ++){
// title属性是获取
var ajaxURL = loadingItems [i] .attr的URL (title)+'?ajaxPageContent =';
$(loadingItems [i])。load(ajaxURL);

}
}

是否有插件我可以继续向队列添加函数,并让它处理它?<​​/ p>

解决方案

诀窍是使用回调。你进行一次ajax调用,并在成功回调时创建下一个调用。



要做到这一点,只需将它们全部添加到队列中并在其周围放置一个包装器,逐个发送它们。



我几天前写了一篇文章。我将在一秒钟内向您展示一个实现。

  //缓冲类。有一个公共附加方法,需要某种任务。 
//构造函数需要一个处理程序,它是一个获取ajax任务
//和回调的方法。 Buffer希望处理程序处理ajax并运行
//回调完成时
函数Buffer(handler){
var queue = [];

函数run(){
var callback = function(){
//当处理程序说它已完成时(即运行回调)
//我们检查对于队列中的更多任务以及是否有任何我们再次运行
if(queue.length> 0){
run();
}
}
//给出队列中的第一项&回调函数
handler(queue.shift(),callback);
}

//将任务推送到队列。如果在推送任务之前队列为空,则
//我们运行任务。
this.append = function(task){
queue.push(task);
if(queue.length === 1){
run();
}
}

}

//小任务包含项目&网址和可选回调
函数任务(item,url,callback){
this.item = item;
this.url = url;
this.callback = callback
}

//小型处理程序,将task.url加载到task.item并在完成后调用回调
//
函数taskHandler(任务,回调){
$(task.item).load(task.url,function(){
//从任务
调用选项回调if(task.callback)task.callback();
//调用缓冲区回调。
callback();
});
}

//使用taskhandler创建一个缓冲区对象
var buffer = new Buffer(taskHandler);

for(i = 0; i< loadingItems.length; i ++){
// title属性是获取
var ajaxURL = loadingItems [i] .attr的URL (title)+'?ajaxPageContent =';
buffer.append(new Task(loadingItems [i],ajaxURL));
}

代码墙的道歉。只需实现自己的任务和处理程序。只要处理程序在完成任务处理时调用第二个参数(回调),缓冲区就会工作。



然后只需传递一个任务和一个处理程序。当ajax返回时,处理程序执行ajax并从缓冲区调用回调。



对于您的具体示例,如果您的加载需要很长时间,那么这将需要很长时间加载所有30的时间.ajax的意思是让服务器并行执行。



在你的情况下,一个更好的解决方案是发出30个请求然后捕获结果并确保您的ajax调用的结果仅按顺序附加到dom。这涉及使用$ .ajax并以某种方式添加跟踪订单。



这样服务器就会尽可能快地完成它,一旦你得到它就可以按顺序服务它。或者,如果你做的事情很快,那么在缓冲区中排队它们就没有任何惩罚。


Hello I am doing a Horizontal scrolling website like: http://vanityclaire.com/

However, rather than having one large HTML file, after the load of the homepage, I am ajaxing in the children of home, using jQuery .load().

At present I for-each div and ajax in ithe url that sits in the title. But the AJAX returns out of order, and as I add more pages don't fancy spanging the server with 30+ http:// requests.

How do I synchronously do the AJAX calls, i.e. wait for the first to comeback before a request another, or even send two at a time.

I have been scouring, and cannot figure out what I need.

This is my HTML:

<div id="mainLayout" class="fullwidth scrollArea">
    <div class="scrollItems">
      <div id="page-1" class="scrollItem" title="/">
        <div>HOME PAGE CONTENT</div>
      </div>
      <div id="page-2" class="scrollItem" title="/Page2.html">
        <div class="loading"> </div>
      </div>
      <div id="page-3" class="scrollItem" title="/Page3.html">
        <div class="loading"> </div>
      </div>

      <div id="page-4" class="scrollItem" title="/Page4.html">
        <div class="loading"> </div>
      </div>
      <div id="page-5" class="scrollItem" title="/Page5.html">
        <div class="loading"> </div>
      </div>
    </div>
  </div>

And my JS:

function s_loadingInitialPages() {
    var loadingItems = new Array();
    $(".scrollArea .scrollItem").each(function () {
        if ($(this).attr('title') != '/') {
            var oDelem = $(this);
            loadingItems.push(oDelem);
            //alert('test');
        }
    });

    for (i = 0; i < loadingItems.length; i++) {
        // title attribute is the URL to get
        var ajaxURL = loadingItems[i].attr("title") + '?ajaxPageContent=';
        $(loadingItems[i]).load(ajaxURL);

    }
}

Is there a plugin I can just keep adding functions to a queue, and let that handle it?

解决方案

The trick is to use the callbacks. You make one ajax call and on its success callback you make the next one.

To do this just add them all to a queue and have a wrapper around it that sends them one by one.

I wrote one a few days ago. I'll show you an implementation in a second.

// Buffer class. Has a public append method that expects some kind of Task.
// Constructor expects a handler which is a method that takes a ajax task
// and a callback. Buffer expects the handler to deal with the ajax and run
// the callback when it's finished
function Buffer(handler) {
    var queue = [];

    function run() {
        var callback = function () {
             // when the handler says it's finished (i.e. runs the callback)
             // We check for more tasks in the queue and if there are any we run again
             if (queue.length > 0) {
                  run();
             }
        }
        // give the first item in the queue & the callback to the handler
        handler(queue.shift(), callback);
    } 

    // push the task to the queue. If the queue was empty before the task was pushed
    // we run the task.
    this.append = function(task) {
        queue.push(task);
        if (queue.length === 1) {
            run();
        }
    }

}

// small Task containing item & url & optional callback
function Task(item, url, callback) {
    this.item = item;
    this.url = url;
    this.callback = callback
}

// small handler that loads the task.url into the task.item and calls the callback 
// when its finished
function taskHandler(task, callback) {
    $(task.item).load(task.url, function() {
        // call an option callback from the task
        if (task.callback) task.callback();
        // call the buffer callback.
        callback();
    });
}

// create a buffer object with a taskhandler
var buffer = new Buffer(taskHandler);

for (i = 0; i < loadingItems.length; i++) {
    // title attribute is the URL to get
    var ajaxURL = loadingItems[i].attr("title") + '?ajaxPageContent=';
    buffer.append(new Task(loadingItems[i], ajaxURL));
}

Apologies for the wall of code. Just implement your own Task and Handler. The Buffer will work as long as the handler calls the second argument (the callback) when it's finished handling the task.

Then just pass it a task and a handler. The handler does the ajax and calls the callback from the buffer when the ajax returns.

For your specific example if what your loading takes a long time then this will take a long time to load all 30. The point of ajax is to have the server do stuff in parallel.

A far better solution in your case is to make 30 requests and then catch the results and make sure the results from your ajax calls are only appended to the dom in order. This involves using $.ajax and adding keeping track of order somehow.

That way the server will do it as fast as it can and you can server it in order once you get it. Alternatively if the things your doing are fast then queuing them in a buffer has no penalty.

这篇关于队列AJAX调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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