I'm grabbing JSON from reddit's API, and placing the JSON objects into a global array.
var stories = [];
var request = new XMLHttpRequest();
request.open('GET', 'http://www.reddit.com/r/news/top.json?limit=5', true);
request.onload = function() {
var rawStories = JSON.parse(request.response);
for (var i in rawStories.data.children) {
var story = {};
story.title = rawStories.data.children[i].data.title;
stories.push(story);
}
};
alert(stories); //Here I am accessing stories in global scope.
The above global alert(stories)
shows the empty initialized stories
array. Moving the alert inside the function displays a properly filled array of objects.
How can I have a globally accessible stories array? My misunderstanding is either in the asynchronous nature of the request.onload
function or I'm having scope trouble (or both).