0

I am trying to retrieve some JSON files. It is not certain which URL will work, therefore I am looking for a way to try all URLs and if one fails, it try another.

URLs like:

www.domain.com/a.json
www.domain.com/b.json
www.domain.com/c.json

var url = "www.domain.com";
var file1 = "/a.json";
var file2 = "/b.json";
var file3 = "/c.json";

$.getJSON( url + file1, function( json ) {
  console.log( "JSON Data: " + json.users[ 3 ].name );
 });

Also the structure of each json file is not the same, so depending on the file i have to have a different way to access it. Let say for file a.json I will access data by json.users[3].name but in file b.json the same data will be accessed by json.sources.users[3].name.

So how can i make a such a method that try the new url whenever it fails? By failing, i mean it may be not existing file (404) or same groin policy error.

Thank in advance.

DannyBoy
  • 434
  • 5
  • 21

2 Answers2

3

You could chain the calls together, so if one call fails, it goes to the next using the jquery fail method on $.getJSON. Something like this:

$.getJSON( url + file1, function( json ) {
    //do something with file1
}).fail(function () {
    $.getJSON( url + file2, function( json ) {
        //do something with file2
    }).fail(function () {
        $.getJSON( url + file3, function( json ) {
            //do something with file3
        })
    });
});

Link to docs: http://api.jquery.com/jquery.getjson/#jqxhr-object

Will P.
  • 8,437
  • 3
  • 36
  • 45
2

Use jQuery's Promise.all implementation: $.when:

var url = "www.domain.com";
var urls = ["/a.json", "/b.json", "/c.json"];
var requests = urls.map(function(path) {
   return $.getJSON(url + path);
});

$.when.apply($, requests).then(function(a_resp, b_resp, c_resp) {
  console.log( "JSON Data: ", a_resp, b_resp, c_resp );
});

This will allow you to wait until all requests have completed and give you access to all of their responses.

Rob M.
  • 35,491
  • 6
  • 51
  • 50