Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
643 views
in Technique[技术] by (71.8m points)

jquery - Call multiple JSON data/files in one getJson request

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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...