gpt4 book ai didi

javascript - 从文件加载的 JSON 对象数组

转载 作者:行者123 更新时间:2023-11-30 17:29:04 24 4
gpt4 key购买 nike

我有一组文件 a.json、b.json、c.json 等,我想将其中包含的数据加载到 JavaScript 中的单个数据结构中。但是,以下代码的最后一行始终返回 0 而不是我期望的 3。我做错了什么?

    files = ["a", "b", "c"];
var dataset = [];

function getObject(file) {
return $.getJSON(file).then(function (data) {
return data;
});
}


for (i = 0; i < files.length; i++) {
getObject(files[i] + ".json").done(function (data) {
dataset.push(data);
});
}

alert(dataset.length)

最佳答案

首先,如果在对 $.ajax 的调用返回后立即运行您的 alert,则数据不可用并且您的变量尚未设置。您必须等到 done 被调用(在对 $.ajax 的方法调用返回很长时间之后,since it's asynchronous)。 How do I return the response from an asynchronous call?

其次,要同步请求,可以使用$.when所以当所有请求都解决时,您会收到通知。 Wait until all jQuery Ajax requests are done?

var files = ["a", "b", "c"];
var dataset = [];
var requests = [];

for (i = 0; i < files.length; i++) {
requests.push($.getJSON(files[i] + ".json") );
}

// $.when may not take the requests as an array, in that case use
// $.when.apply($, requests).done();
$.when(requests).done(function() {
for (var i=0; i < arguments.length; i++) {
dataset.push(arguments[i]);
}
alert('All three received, dataset length is ' + dataset.length)
})

关于javascript - 从文件加载的 JSON 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23571800/

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