I am aware this (or a similar) question has been asked a number of times. Still I do not understand how to get the loaded object outside of the scope of the function that creates it.
In particular if I do
var xmlhttp = new XMLHttpRequest();
var url = "lineJSON.json";
var myArr= new Array();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myArr = JSON.parse(this.responseText);
console.log(myArr[0].url); //here it give the right output
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
console.log(myArr[0].url); // Cannot read property 'url' of undefined
in the second console.log myArr is clearly not working, its url
key it's undefined!
How do I make myArr
available outside of that function
?
FYI the json is
[
{
"display": "JavaScript Tutorial",
"url": "http://www.w3schools.com/js/default.asp"
},
{
"display": "JavaScript Tutorial",
"url": "http://www.w3schools.com/js/default.asp"
}
]
If possible I would like to not use jQuery.