Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call multiple JSON data/files in one getJson request

Tags:

json

jquery

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

like image 957
Giorgia Sambrotta Avatar asked Sep 26 '13 10:09

Giorgia Sambrotta


1 Answers

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.

like image 156
T.J. Crowder Avatar answered Oct 12 '22 18:10

T.J. Crowder