Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: XMLHttpRequest for json outside the scope

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.

like image 651
goldensausage Avatar asked Sep 14 '25 14:09

goldensausage


1 Answers

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
    }
}
like image 197
Luke Lee Avatar answered Sep 16 '25 06:09

Luke Lee