返回一个对象javascript
问题描述:
嗨在那里我试图从loadData函数返回一个对象,但我在FF中获得“obj未定义”和在chrome中获取“Uncaught ReferenceError”。我读到如果声明了一个没有前缀的变量“ var它被认为是全球性的“范围”obj“应该是全球性的,并且应该从json响应返回数据。我不知道我在哪里出错我是Javascript新手。感谢所有帮助。返回一个对象javascript
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>
....
答
这是因为onreadystatechange
函数是异步的。你需要做的是这样的:
function loadData(callback) {
xmlhttp.onreadystatechange=function() {
...
callback(data);
}
}
答
您从loadData函数返回OBJ,并且当函数返回obj是尚未确定。你需要在回调函数本身中使用obj做一些事情 - 也许将它传递给第三个函数,该函数实际上处理和处理数据。
答
AJAX调用是异步的。代码不会等待响应。它继续执行下一个代码,同时等待作为响应。这意味着return obj
在它实际填充数据之前被执行。
你应该做的是交出了“回调”,基本上是一个在接收到数据时执行功能:
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);
});
+0
感谢您的解释。 – 2012-04-29 01:38:22
感谢我做这个工作的快速反应。 – 2012-04-29 01:37:51