So i was trying to get json data and storing it in a variable. The problem is that everything inside the .onReadyStateChange block is like a blackhole, nothing gets out of there so I can't retrieve information. I can call functions from within that block and it will work, but anything i try to save to an outside entity will result in null, even if that variable is of the window scope.
var globalVar;
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var foodsArray = JSON.parse(this.responseText);
globalVar = JSON.stringify(foodsArray);
}
}
console.log(globalVar);
//result will be null, so will foodsArray had I made it global
So my question is, is there any way to save that information outside of that block? Thanks.
First, you need to know the principle of the ajax. you konw, the ajax is an async function, so when you haven't gotten the return value, 'console.log(globalVar)' has been executed. So you should write in the way:
var globalVar;
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var foodsArray = JSON.parse(this.responseText);
globalVar = JSON.stringify(foodsArray);
console.log(globalVar); // you can get the result
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With