【问题标题】:Trigger callback after getting multiple json files asynchronously异步获取多个json文件后触发回调
【发布时间】:2014-06-27 21:32:34
【问题描述】:
我有 3 个来自旧论坛的 JSON 文件,其中包含:成员、主题和回复。
现在我想通过 javascript/jquery 获取 3 个 json 文件来在网站上呈现它。
我可以通过首先获取成员、返回时获取主题和返回时获取回复来同步完成。但我想异步执行。
有没有像 $.getJson 这样的东西,它接受多个 URL,然后返回一个结果数组?像一个富有想象力的 $.getJson([url1,url2,url3],callBackFunction)
【问题讨论】:
标签:
javascript
jquery
json
asynchronous
【解决方案1】:
使用jQuery.when:
var A = $.getJSON(url1);
var B = $.getJSON(url2);
var C = $.getJSON(url3);
$.when(A,B,C).done(function(aResult, bResult, cResult){//when all request are successful
console.log([aResult[0],bResult[0],cResult[0]]);
});
【解决方案2】:
您可能想使用$.when 之类的东西。它允许您列出一系列承诺和所有完成时的回调。除了列出承诺之外,您还可以使用apply 将数组传递给$.when。例如:
var endpoints = [url1, url2, url3];
var promises = [];
// Simple function that takes an endpoint and returns a promise.
// I've used $.ajax here, but all of jQuery's
// XHR objects use the promise interface
function getData(endpoint) {
return $.ajax({
type: 'GET',
url: endpoint,
dataType: 'jsonp'
});
}
// Build an array of promises.
for (var i = 0, l = endpoints.length; i < l; i++) {
promises.push(getData(endpoints[i]));
}
// Pass the promises to `$.when`. Show the returned data when
// the promises have all finished processing.
$.when.apply(null, promises).then(function (data1, data2, data3) {
console.log(data1, data2, data3);
});
【解决方案3】:
与许多 jQuery 方法一样,$.getJson() 异步加载数据。这意味着您可以调用该函数而不是阻止执行。一旦内容加载完毕,就会触发你的回调函数。
举个简单的例子:
console.log( "loading first file..." );
$.getJSON( "file1.js", function( json ) {
console.log( "first file loaded!" );
});
console.log( "loading second file..." );
$.getJSON( "file2.js", function( json ) {
console.log( "second file loaded!" );
});
console.log( "loading third file..." );
$.getJSON( "file3.js", function( json ) {
console.log( "third file loaded!" );
});
您将看到所有“加载”控制台日志将立即输出,并且 file1/2/3 的内容将立即开始下载。
您可以做的是让所有回调执行相同的函数,该函数将存储已加载资源的计数器,一旦所有资源都已加载,您就可以调用最终回调:
$.getJSON( "file.js", function( json ) {
// Do whatever you want with the `json` parameter
resource_loaded(); // monitor loaded resources.
});
var total_resources = 0
var loaded_resources = 0;
function resource_loaded(){
loaded_resources += 1;
if ( loaded_resources === total_resources ){
final_callback();
}
}