嗨,我试图从loadData函数返回一个对象,但在FF中得到“未定义obj”,在chrome中得到“Uncaught ReferenceError”。我读到,如果声明一个不带前缀“var”的变量,则假定它是全局变量““obj”的范围应该是全局的,并且应该从json响应中返回数据。我不知道我要去哪里错了,我是Java语言的新手。感谢所有帮助。

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);
  }
}

10-05 20:55
查看更多