我有我认为一个全局变量的问题。观看这个:AJAX全局变量? (Javascript)
function more_elems() {
var ret = [];
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var JSONObject = JSON.parse(xmlhttp.responseText);
for (i=0;i<5;i++){
ret[i] =
{
id: JSONObject[i].id,
nombre: JSONObject[i].nombre,
mensaje: JSONObject[i].mensaje,
ult_m: JSONObject[i].ultima_modificacion
};
}
alert(ret);
}
}
xmlhttp.open("GET","somewesite.com",true);
xmlhttp.send();
return ret;
所以即时尝试返回ret数组,但它返回undefined。但是,如果我在xmlhttp.onreadystatechange = function()中做了一个警报,它确实显示了带有json对象的数组。我不确定问题是什么= /。
在此先感谢。
你需要了解的回调是什么... http://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-他们是不同的从调用o – rafaelcastrocouto
即使你的变量范围很难是正确的,请看看[this](http://stackoverflow.com/q/500431/2752041)。它可以帮助你理解更好的变量范围和全局变量。 ;) – mathielo