等待多个Ajax调用 [英] Waiting for multiple Ajax calls

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

问题描述

我在下面有一个循环,它遍历div#canvas(与HTML5的画布无关)来查找必须加载的元素.基本上,如果元素具有目标属性(第1行)并且指向的目标(target $)不在div#canvas中(第6行),则会启动Ajax $ .post请求(第7行)以将缺少的目标引入从服务器添加到div#canvas.

I have an each-loop, below, that goes through div#canvas (nothing to do with HTML5's canvas) looking for elements that have to be loaded. Basically, if an element has a target attribute (line 1) and the target pointed to (target$) is not in div#canvas (line 6) an Ajax $.post request is launched (line 7) to bring the missing target in from the server and prepend it to div#canvas.

$("#canvas .active[target]").each(function() { 
    this$ = $(this);
    targetName = this$.attr('target'); 
    target$ = $('div[name=' + targetName + ']');

    if (target$.length == 0) {
        $.post('loadData.php', { fileName : targetName + '.xml' },function(xml) {  
            canvasData$ = $(xml).find("canvasData");  
            $('#canvas').prepend(canvasData$);      
        });
    }
});   

所有这些丢失的目标均已加载后,我想发出一个Ajax请求以将所有div#canvas发送到服务器.该呼叫看起来像这样:

When all of these missing targets have been loaded I want to issue an Ajax request to send all of div#canvas to the server. That call looks like this:

Status$.load('writePage.php', { 
    pageName: pageName, 
    seg1: seg1, 
    canvas: canvasOuterHTML,
    seg2: seg2
});

有人可以建议最好的方法来推迟对writePage的最终调用,直到所有丢失的目标读均已完成?

Could someone suggest the best way to hold off the final call to writePage until all of the missing target reads have completed?

谢谢.

推荐答案

使用$ .when

var array = [];
$("#canvas .active[target]").each(function() { 
    this$ = $(this);
    targetName = this$.attr('target'); 
    target$ = $('div[name=' + targetName + ']');

    if (target$.length == 0) {
        var ajax = $.post('loadData.php', { fileName : targetName + '.xml' },function(xml) {  
            canvasData$ = $(xml).find("canvasData");  
            $('#canvas').prepend(canvasData$);      
        });
        array.push(ajax)
    }
});
$.when.apply($, array).done(function(){
    //do something
})

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

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