joker stream joker stream - 16 days ago 6
Javascript Question

How to store $.getJSON object in global variable and navigate through it later

I'm experimenting with JQuery and trying to create a function to get dynamic data from a JSON returned API and store it in a global variable (I don't know if this is the right/best way to do this).

What I have so far is

function getdata(url){
var data = $.ajax({
type: 'GET',
url: url
});
return data;
};


So far everything works fine, but this returns an object with a "responseJSON" key and I can't seem to find a way to navigate to this key and then do a $.each loop through the arrays in it.

So the questions are:


  1. Is this the right / way ( if not please explain your answer)

  2. How do you navigate through a multidimensional object containing arrays in the "responseJSON" key.


Answer

Another approach is to pass a callback to your function so you can set the response handler within the function and less code when you call your getData method

function getdata(url, callback){
    var data = $.ajax({
                type: 'GET',
                url: url
            }).done(callback).error(function(){
               alert('Oppps...something went wrong')
            });
    return data;
};


getData('urlstring', function(data){
   /* doSomething with data */
})
Comments