When my page loads, I want to immediately pull in JSON data from another server using $.ajax(), and I want to be able to access all the data without having to re-request the json file. The problem is, when I assign the data to a variable, the scope of that variable is confined to the $.ajax() function and I can't access it elsewhere...
It seems like since I have already loaded that information, I should be able to use it as many times as I need too without having to re-request it over and over again (slow). Using simple reddit.json request for example below
$(document).ready(function(){
$.ajax({
type: "GET",
url: 'https://www.reddit.com/.json',
timeout:3000,
dataType: 'JSON',
jsonpCallback: 'callback',
success: function(data) {
console.log(data);
var myData = data; //this variable is confined :(
},
error: function(){
console.log('error');
}
});
});
If I run it outside of the document.ready(), then I can get to it globally, but I didn't know if that was cool or not, or like best practices, you know...
Whats the best way to access an already-loaded json object outside of the scope of the function that made it's initial request? Or is it even possible...?