This question already has an answer here:
这个问题在这里已有答案:
- How do I return the response from an asynchronous call? 31 answers
如何从异步调用返回响应? 31个答案
I am aware this (or a similar) question has been asked a number of times. Still I do not understand how to get the loaded object outside of the scope of the function that creates it.
我知道这个(或类似的)问题已被多次询问过。我仍然不明白如何将加载的对象置于创建它的函数范围之外。
In particular if I do
特别是如果我这样做的话
var xmlhttp = new XMLHttpRequest();
var url = "lineJSON.json";
var myArr= new Array();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myArr = JSON.parse(this.responseText);
console.log(myArr[0].url); //here it give the right output
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
console.log(myArr[0].url); // Cannot read property 'url' of undefined
in the second console.log myArr is clearly not working, its url
key it's undefined!
在第二个console.log myArr显然不工作,它的url键是未定义的!
How do I make myArr
available outside of that function
?
如何在该功能之外使myArr可用?
FYI the json is
仅供参考,json是
[
{
"display": "JavaScript Tutorial",
"url": "http://www.w3schools.com/js/default.asp"
},
{
"display": "JavaScript Tutorial",
"url": "http://www.w3schools.com/js/default.asp"
}
]
If possible I would like to not use jQuery.
如果可能的话我想不使用jQuery。
1 个解决方案
#1
0
You can read property url, because it's undefined. It's undefined, becuse when you try acces to it array "myArr" is still empty. You using XMLHttpRequest asynchronously, so browser doesn't wait for response and executes next commands. You shulde use callback function or change
您可以读取属性URL,因为它未定义。它是未定义的,因为当你尝试访问它时,“myArr”仍然是空的。您异步使用XMLHttpRequest,因此浏览器不会等待响应并执行下一个命令。你shulde使用回调函数或更改
xmlhttp.open("GET", url, true);
to:
xmlhttp.open("GET", url, false);
But it's not the best solution. When request get error whole script will be stopped.
但这不是最好的解决方案。当请求获取错误时,将停止整个脚本。
#1
0
You can read property url, because it's undefined. It's undefined, becuse when you try acces to it array "myArr" is still empty. You using XMLHttpRequest asynchronously, so browser doesn't wait for response and executes next commands. You shulde use callback function or change
您可以读取属性URL,因为它未定义。它是未定义的,因为当你尝试访问它时,“myArr”仍然是空的。您异步使用XMLHttpRequest,因此浏览器不会等待响应并执行下一个命令。你shulde使用回调函数或更改
xmlhttp.open("GET", url, true);
to:
xmlhttp.open("GET", url, false);
But it's not the best solution. When request get error whole script will be stopped.
但这不是最好的解决方案。当请求获取错误时,将停止整个脚本。