jQuery顺序呈现从ajax请求中获取的项目

时间:2012-04-06 12:08:24

标签: jquery ajax sequential

我有一个显示对象列表的页面。这些列表中的每一个都来自ajax调用。我如何确保它们按顺序呈现?

我尝试使用here显示的技术,但是如果其中一个请求失败,它会拒绝其余的请求。我的数据不依赖于之前的数据,那么我该如何修改示例和处理错误呢?

3 个答案:

答案 0 :(得分:2)

你知道,在另一个post中,我写了这个小解析器类,但我喜欢这种管道的想法。我不知道我非常喜欢这个例子,但稍微调整一下,我觉得它会很好用。我承认,我还没有测试过这个。

var urls = ["path1","path2","path3"]; // Output from string.split()
var chain = $.Deferred(); // Create the root of the chain.
var promise = chain; // Placeholder for the promise

// Build the chain
jQuery.each(urls,function(index,elem){
    // Pipe the response to the "next" function
    promise = promise.pipe(function(response)
    {
        var myurl = elem; // Get the current part
        var newPromise = $.Deferred();
        $.ajax 
        ({
           type: "GET",
           url: myurl
        }).done(function(data){  
          //these are your normal ajax success function params, IIRC
           //do stuff with response
        }).fail(function(){
           //oops, it failed, oh well
           //do stuff on failure 
        }).always(function() {
           //but always resolve the sequencing promise
           newPromise.resolve();            
        });
        return newPromise;
    })
});

chain.resolve();

编辑:这是一个带有模拟ajax请求的{JSFiddle} http://jsfiddle.net/jfcox/gFLhK/。正如你所看到的,它都是排序的。

编辑II:评论中略有调整。请注意,您应该能够通过将任何内容传递给您的解析调用来将信息传递给您的下一个承诺...

编辑III:根据Dave的建议修改。要进一步区分问题,您可以在ajax请求中使用always

答案 1 :(得分:0)

您可以将响应列表保存在数组中

function response () {
   responseArray[i] = response; // Where i is the sequence number of request and response;
   responseHandler(); // Ping some function which can take the response in the order and process it.
}

答案 2 :(得分:0)

您是否尝试过使用jQuery.when?
http://api.jquery.com/jQuery.when/

示例
http://jsfiddle.net/94PGy/4/

在多个Deferreds案例中,其中一个Deferreds被拒绝,jQuery.when立即触发其主Deferred的failCallbacks。请注意,此时某些延迟可能仍未解决。如果您需要为此情况执行其他处理,例如取消任何未完成的ajax请求,则可以在闭包中保留对基础jqXHR对象的引用,并在failCallback中检查/取消它们。