简体   繁体   中英

Tranfer data from local variable to global in javascript

I have some problem with transfer of variable outside the function. It's seems to be very simple but I have some problem with it.

var myJson;
var url = "https://openbook.etoro.com/api/Markets/Symbol/?name=" + symbol;
var xhr = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));
xhr.onreadystatechange = XHRhandler;
xhr.open("GET", "proxy.php?url=" + url, true);
xhr.send(null);

function XHRhandler() {

    if (xhr.readyState == 4) {

        var json;
        if (JSON && JSON.parse) {
            json = JSON.parse(xhr.responseText);
        } else {
            eval("var json = " + xhr.responseText);
        }
        console.log(json);
        myJson= json;
        xhr = null;
    }

}
console.log(myJson);

What I need is to pass the data from local variable json to global myJson; But when i do console.log(myJson) i get undefined. What is the problem?

Thank you

Try moving the statement console.log(myJson); inside your if condition or alternately initialize your variable with some value. It seems your statement is getting called before it is getting populated with any value.

The XMLHttpRequest is async so it is not done yet when you try to write the myJson variable to console. Wrap it in a function and call that function after the XMLHttpRequest is completed instead.

var myJson;
var url = "https://openbook.etoro.com/api/Markets/Symbol/?name=" + symbol;
var xhr = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));
xhr.onreadystatechange = XHRhandler;
xhr.open("GET", "proxy.php?url=" + url, true);
xhr.send(null);

function XHRhandler() {

    if (xhr.readyState == 4) {

        var json;
        if (JSON && JSON.parse) {
            json = JSON.parse(xhr.responseText);
        } else {
            eval("var json = " + xhr.responseText);
        }
        console.log(json);
        myJson= json;
        xhr = null;
        writeToConsole();
    }

}

function writeToConsole() {
    console.log(myJson);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM