gpt4 book ai didi

javascript - jquery 从多个 ajax 调用中收集

转载 作者:行者123 更新时间:2023-11-30 08:51:50 24 4
gpt4 key购买 nike

我正在尝试使用 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");

基本上,如果满足某些条件,那么我会立即添加内容,否则我想将其添加到内容的末尾,以及所有其他“已保存”的内容。

我想做的事情可行吗?如果是,怎么办?

最佳答案

新答案:

我会以不同的方式处理这个问题。而不是使用 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");
});

原答案:

问题是 $.ajax 是异步的。尝试替换这一行:

html += "<div>" + item.data + "</div>";

有了这个:

$("<div>" + item.data + "</div>").appendTo("#content");

关于javascript - jquery 从多个 ajax 调用中收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17181842/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com