返回一个对象javascript
您好,我正试图从loadData函数返回一个对象,但我在FF中得到“obj未定义”,在chrome中得到“Uncaught ReferenceError”。我了解到,如果您声明一个没有前缀“var”的变量,则假定它是全局变量,“obj”的范围应该是全局的,并且应该从json响应返回数据。我不知道哪里出了问题,我是Javascript新手。感谢所有的帮助返回一个对象javascript,javascript,closures,Javascript,Closures,您好,我正试图从loadData函数返回一个对象,但我在FF中得到“obj未定义”,在chrome中得到“Uncaught ReferenceError”。我了解到,如果您声明一个没有前缀“var”的变量,则假定它是全局变量,“obj”的范围应该是全局的,并且应该从json响应返回数据。我不知道哪里出了问题,我是Javascript新手。感谢所有的帮助 function loadData() {..... xmlhttp.onreadystatechange=function(){
function loadData()
{.....
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
personInfo=xmlhttp.responseText;
obj = JSON.parse(personInfo);
alert(obj[2].name);
}
};
return obj;//"obj is not defined" in FF and "Uncaught ReferenceError" in chrome
}
<h2>AJAX</h2>
<button type="button" onclick="loadData()">Request data</button>
<div id="myDiv"></div>
....
函数loadData()
{.....
xmlhttp.onreadystatechange=函数(){
if(xmlhttp.readyState==4&&xmlhttp.status==200)
{
personInfo=xmlhttp.responseText;
obj=JSON.parse(personInfo);
警报(obj[2]。名称);
}
};
返回obj;//“obj未定义”在FF中,以及“未捕获引用错误”在chrome中
}
AJAX
请求数据
....
这是因为onreadystatechange
函数是异步的。您需要执行以下操作:
function loadData(callback) {
xmlhttp.onreadystatechange=function() {
...
callback(data);
}
}
您正在从loadData函数返回obj,当该函数返回obj时,obj尚未定义。您需要在回调函数本身中使用obj做一些事情——可能会将其传递给第三个函数,该函数实际处理数据并执行某些操作。AJAX调用是异步的。代码不会等待响应。它在等待响应的同时继续执行下一个代码。这意味着
returnobj
在实际填充数据之前执行
您应该做的是移交一个“回调”,基本上是一个在收到数据时要执行的函数:
function loadData(callback){
...
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
//execute callback, passing it the parsed JSON
callback(JSON.parse(xmlhttp.responseText));
}
}
//execute send here
}
//call loadData, passing it a callback function
//this function will be executed when response is received
//and the data will be provided as "returnedData"
loadData(function(returnedData){
//use data
alert(returnedData[2].name);
});