Search code examples
javascriptgetjson

Can a getJSON url string be dynamically created?


Is it possible to replace this approach for the url string:

    $.when($.getJSON(url0), $.getJSON(url1), $.getJSON(url2), $.getJSON(url3)).then(function() { ...

using another JSON file?

Why? The number of url items changes and I want to pull them from a single file without revising where this code lives each time. I could be dealing with url0-url3 or url0-40 then backto url0-url20.

The current approach forces a manual update of the array that's used to build the url string plus an update to the function.

What do you suggest?


Solution

  • Maybe something like this?

    var urls = [
      'http://jsonplaceholder.typicode.com/posts/18',
      'http://jsonplaceholder.typicode.com/posts/37'
    ];
    
    var results = {};
    
    function saveResult(urlPath, data) {
      results[urlPath] = data;
    }
    
    function f() {
      ($.when).apply(this, Array.prototype.slice.call(arguments).map(function(urlPath) {
        return $.getJSON(urlPath, saveResult.bind(this, urlPath));
      })).then(function() {
       console.log('Completed fetch', results); 
      });
    }
    
    f.apply(this, urls);
    

    UPDATE: If you want to grab the urls from a file, something like this should work:

    function makeUrls(cb) {
      var urls = [];
      var idString1 = '???', idString2 = '????';
      $.when($.getJSON('new_name2.json')).then(function(c) {
        $.each(c.myStuff, function(f, e) {
          urls.push(idString1 + e.id + idString2);
        });
        cb(urls);
      });
    }
    
    var results = {};
    
    function saveResult(urlPath, data) {
      results[urlPath] = data;
    }
    
    function f() {
      ($.when).apply(this, Array.prototype.slice.call(arguments).map(function(urlPath) {
        return $.getJSON(urlPath, saveResult.bind(this, urlPath));
      })).then(function() { console.log('DID IT!', results); });
    }
    
    makeUrls(function(urls) {
      f.apply(this, urls);
    });