jquery从多个ajax调用中收集

jav*_*y79 1 javascript jquery

我试图使用jquery和ajax从几个url收集数据,然后从中创建内容.但是,我必须遗漏一些东西,因为它似乎不起作用.

我有这样的事情:

var html = "";
function loadByUrl(url) {
    $.ajax({
        url: url, 
        dataType: 'json',
        async: false,
        success: function(json) {
          $.each(json.data.children, function(i,item){
            if( someCondition ) {
                $(item.data).appendTo("#content");
            } else {
                html += "<div>" + item.data + "</div>"; 
            }
          }
        }
    });
}

loadByUrl("http://fake1.com");
loadByUrl("http://fake2.com");
loadByUrl("http://fake3.com");
$(html).appendTo("#content");
Run Code Online (Sandbox Code Playgroud)

基本上,如果满足某些条件,那么我将立即添加内容,否则我想在内容的末尾添加所有其他"已保存"的内容.

我正在尝试做什么?如果是这样,怎么样?

Int*_*ual 5

新答案:

我会以不同方式处理这个问题.而不是使用async: false,通常不赞成(它甚至在最新版本的jQuery中被弃用),我会$.when用来实现相同的效果.

// return a promise
function loadByUrl(url) {
    return $.ajax({
        url: url, 
        dataType: 'json'
    });
}

// handle processing the data in a separate function
function processData(data) {
    var result = '';
    $.each(data.children, function(i,item){
        if( someCondition ) {
             $(item.data).appendTo("#content");
        } else {
            result += "<div>" + item.data + "</div>"; 
        }
    }
    return result;
}

// use when to ensure all of the AJAX requests execute before
// doing anything with their results
$.when(loadByUrl("http://fake1.com"), loadByUrl("http://fake2.com"), loadByUrl("http://fake3.com")).done(function(fake1, fake2, fake3) {
    // this function is called after all three AJAX promises are resolved
    var html = '';

    html += processData(fake1[0]);
    html += processData(fake2[0]);
    html += processData(fake3[0]);

    $(html).appendTo("#content");
});
Run Code Online (Sandbox Code Playgroud)

原始答案:

问题$.ajax是异步的.尝试替换此行:

html += "<div>" + item.data + "</div>";
Run Code Online (Sandbox Code Playgroud)

有了这个:

$("<div>" + item.data + "</div>").appendTo("#content");
Run Code Online (Sandbox Code Playgroud)

  • 他在'ajax`选项中有`async:false,` (2认同)