如何将JSON数据分配给全局变量?

时间:2019-12-01 22:05:31

标签: json

为什么变量未定义以及如何将json数据放入全局变量?

var responce;

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if(this.readyState == 4 && this.status === 200) {
        responce = JSON.parse(xhttp.responseText);
        console.log(responce.trainers);
    }
}

xhttp.open("GET", "trainers.json", true);
xhttp.send();

console.log(responce); // undefined

1 个答案:

答案 0 :(得分:0)

触发onreadystatechange回调时,响应变量将获得一个值...在此之前...该变量未定义...

您需要在回调中访问它 即将console.log(response)放入回调中...

xhttp.onreadystatechange = function() { 
    if(this.readyState == 4 && this.status === 200) { 
        responce = JSON.parse(xhttp.responseText);
        console.log(responce); // Value will be defined at this point
        console.log(responce.trainers); 
    } 
}