Patrioticcow
Patrioticcow

Reputation: 27058

How to load data from 2 json files using jquery?

I have two json files and I want to do an ajax call to both of them.

$.getJSON('http://www.example.com/contest_media', function(data) { do something });
$.getJSON('http://www.example.com/contest', function(data) { do something });

I want it to become something like:

$.getJSON(['http://www.example.com/contest_media', 'http://www.example.com/contest'], function(data) { do something});

I am also using $.each(data, function(i,item) {} so I can't do:

$.getJSON('http://www.example.com/contests', function(data) { 
$.each(data, function(i,item) {
    do something
    $.getJSON('http://www.example.com/contest_media', function(data) {do something });
}
});

Here the contest_media won't keep track of contests.

I basically want to use data from both json files in the same $.each. Any ideas?

Upvotes: 2

Views: 4076

Answers (2)

Owen
Owen

Reputation: 84513

Can you not just nest it? I imagine you need to rely on data from both of them anyhow.

$.getJSON('http://example.com/contest_media', function(data) {
 // do basic stuff
 $.getJSON('http://example.com/contest', function(data) {
   // do more stuff now that you have both pieces of data
 });
});

Upvotes: 0

T. Stone
T. Stone

Reputation: 19495

I believe this can be done with $.when. In your case your code would probably look something like...

$.when(
    $.getJSON('http://www.example.com/contest_media'),
    $.getJSON('http://www.example.com/contest')
).done(function(contestMedia, contest) {

    // do something    
    // contestMedia = [ "success", statusText, jqXHR ]
    // contest = [ "success", statusText, jqXHR ]

    // response data can be gotten with contest[2].responseText

});

jQuery doc page for $.when

Note that this requires jQuery version 1.5.

Upvotes: 2

Related Questions