为什么变量未定义以及如何将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
答案 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);
}
}