异步获取多个json文件后触发回调

时间:2014-03-17 10:58:17

标签: javascript jquery json asynchronous

我有来自旧论坛的3个JSON文件,其中包含:成员,主题和回复。 现在我想通过javascript / jquery获取3个json文件在网站上呈现它。

我可以通过首先获取成员,返回获取主题并返回获取回复时同步执行。但我想以异步方式进行。

是否有类似$ .getJson的内容,它会占用多个网址,然后返回一系列结果?就像一个富有想象力的$ .getJson([url1,url2,url3],callBackFunction)

3 个答案:

答案 0 :(得分:5)

使用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]]);
});

答案 1 :(得分:1)

你可能想要使用像$.when这样的东西。它允许您列出一系列承诺和回调,以便它们全部完成。您可以使用$.when将数组传递给apply,而不是列出承诺。例如:

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);
});

答案 2 :(得分:-1)

与许多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!" );
});

你会看到你所有的#34; loading&#34;控制台日志将立即输出,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();
  }
}