在一个getJson请求中调用多个JSON数据/文件

我有这个代码:

var graphicDataUrl = 'templating/graphic-data.json'; var webDataUrl = 'templating/web-data.json'; var templateHtml = 'templating/templating.html'; var viewG = $('#view-graphic'); var viewW = $('#view-web'); $.getJSON(dataUrls, function(data) { $.get(templateHtml, function(template) { template = Handlebars.compile(template); var example = template({ works: data }); viewG.html(example); viewW.html(example); }); }); 

调用两个dataUrl JSON并使用它们的数据以便在我的页面上的两个不同div(#viewW和#viewW)中显示它们的最佳方法是什么?

最好的方法是单独执行每个操作,并处理错误情况:

 $.getJSON(graphicDataUrl) .then(function(data) { // ...worked, put it in #view-graphic }) .fail(function() { // ...didn't work, handle it }); $.getJSON(webDataUrl, function(data) { .then(function(data) { // ...worked, put it in #view-web }) .fail(function() { // ...didn't work, handle it }); 

这允许请求并行发生,并在每个请求完成时尽快更新页面。

如果你想并行运行请求但等待更新页面直到它们完成,你可以使用$.when

 var graphicData, webData; $.when( $.getJSON(graphicDataUrl, function(data) { graphicData = data; }), $.getJSON(webDataUrl, function(data) { webData = data; }) ).then(function() { if (graphicData) { // Worked, put graphicData in #view-graphic } else { // Request for graphic data didn't work, handle it } if (webData) { // Worked, put webData in #view-web } else { // Request for web data didn't work, handle it } }); 

…但是,由于您在第一次请求返回时没有更新,但页面可能看起来响应性较低,但只有在两者都这样做时才会更新。

万一它对任何可能遇到这种情况的人都有用 – 并且由于jQuery中的Promise的进步 – TJ Crowder的答案现在可以改进为一个简洁而通用的function:

 /** * Load multiple JSON files. * * Example usage: * * jQuery.getMultipleJSON('file1.json', 'file2.json') * .fail(function(jqxhr, textStatus, error){}) * .done(function(file1, file2){}) * ; */ jQuery.getMultipleJSON = function(){ return jQuery.when.apply(jQuery, jQuery.map(arguments, function(jsonfile){ return jQuery.getJSON(jsonfile); })).then(function(){ var def = jQuery.Deferred(); return def.resolve.apply(def, jQuery.map(arguments, function(response){ return response[0]; })); }); }; 

然而,关于不向用户提供任何反馈的观点 – 在等待满载时 – 是一个好的。 因此,对于那些喜欢提供响应式反馈的人来说,这是一个支持进度的稍微复杂的版本。

 /** * Load multiple json files, with progress. * * Example usage: * * jQuery.getMultipleJSON('file1.json', 'file2.json') * .progress(function(percent, count, total){}) * .fail(function(jqxhr, textStatus, error){}) * .done(function(file1, file2){}) * ; */ jQuery.getMultipleJSON = function(){ var num = 0, def = jQuery.Deferred(), map = jQuery.map(arguments, function(jsonfile){ return jQuery.getJSON(jsonfile).then(function(){ def.notify(1/map.length * ++num, num, map.length); return arguments; }); }) ; jQuery.when.apply(jQuery, map) .fail(function(){ def.rejectWith(def, arguments); }) .done(function(){ def.resolveWith(def, jQuery.map(arguments, function(response){ return response[0]; })); }) ; return def; }; 

这段代码很简单,您可以在一个函数中同时访问这两个响应:

 $.when( $.getJSON(graphicDataUrl), $.getJSON(webDataUrl) ).done(function(data1, data2) { console.log(data1[0]); console.log(data2[0]); });