我有我認爲一個全局變量的問題。觀看這個: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