简体   繁体   English

在javascript中将数据从局部变量传递到全局

[英]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; 我需要的是将数据从局部变量json传递到全局myJson; But when i do console.log(myJson) i get undefined. 但是当我做console.log(myJson)时,我变得不确定。 What is the problem? 问题是什么?

Thank you 谢谢

Try moving the statement console.log(myJson); 尝试移动语句console.log(myJson); inside your if condition or alternately initialize your variable with some value. 在if条件中,或用一些值替代地初始化变量。 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. XMLHttpRequest是异步的,因此当您尝试将myJson变量写入控制台时,它尚未完成。 Wrap it in a function and call that function after the XMLHttpRequest is completed instead. 将其包装在一个函数中,并在XMLHttpRequest完成后调用该函数。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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