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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19026331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:02:50  来源:igfitidea点击:

Call multiple JSON data/files in one getJson request

jsonjquery

提问by Giorgia Sambrotta

I have this code:

我有这个代码:

var graphicDataUrl = 'graphic-data.json';
var webDataUrl = 'web-data.json';
var templateHtml = '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);
    }); 
});

What is the best way for call both webDataUrl and graphicDataUrl JSONs and use their data in order to display them in two different div (#viewG and #viewW)?

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

回答by T.J. Crowder

The best way is to do each one individually, and to handle error conditions:

最好的方法是单独做每一个,并处理错误情况:

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

That allows the requests to happen in parallel, and updates the page as soon as possible when each request completes.

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

If you want to run the requests in parallel but waitto update the page until they bothcomplete, you can do that with $.when:

如果您想并行运行请求但等待更新页面直到它们完成,您可以使用$.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
    }
});

...but the page may seem less responsive since you're not updating when the first request comes back, but only when both do.

...但是页面可能看起来响应速度较慢,因为您没有在第一个请求返回时进行更新,而只有在两个请求都返回时才进行更新。

回答by Pebbl

Just in case it is useful to anyone else who may come across this — and thanks to the Promise advances in jQuery — T.J. Crowder's answer can now be improved into one succinct and general function:

以防万一它对可能遇到此问题的任何其他人有用 - 并且由于 jQuery 中的 Promise 进步 - 现在可以将 TJ Crowder 的答案改进为一个简洁和通用的功能:

/**
 * 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];
    }));
  });
};

However the point about not giving any feedback to the user — whilst waiting for the full load — is a good one. So for those that prefer to give responsive feedback, here's a slightly more complicated version that supports progress.

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

/**
 * 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;
};

回答by Nabi K.A.Z.

This code is simple and you can access both response together in one function:

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

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