在一个getJson请求中调用多个JSON数据/文件 [英] Call multiple JSON data/files in one getJson request

查看:182
本文介绍了在一个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)中显示它们的最佳方法是什么?

What is the best way for call the both dataUrl JSONs and use their data in order to display them in two different div (#viewW and #viewW) on my page?

推荐答案

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

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 wait to update the page until they both complete, you can do that with $.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.

这篇关于在一个getJson请求中调用多个JSON数据/文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆