2014-02-26 246 views
0

我有我認爲一個全局變量的問題。觀看這個: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對象的數組。我不確定問題是什麼= /。

在此先感謝。

+1

你需要了解的回調是什麼... http://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-他們是不同的從調用o – rafaelcastrocouto

+0

即使你的變量範圍很難是正確的,請看看[this](http://stackoverflow.com/q/500431/2752041)。它可以幫助你理解更好的變量範圍和全局變量。 ;) – mathielo

回答

0

Ajax是異步的。因此ret array將不會被設置,當您在xmlhttp.send().

後立即調用ret array設置的值有任何mehtod和傳遞值。泰類似下面,

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

     } 
     onAjaxSuccess(ret); 
     } 
    } 

function onAjaxSuccess(arr){ 
    alert(arr); 
} 
+0

是的,這工作!謝謝。但是,如果我嘗試返回主函數 - >函數more_elems(),會怎麼樣呢?因爲這就是我試圖達到的目標。在該函數上返回ret數組。 –

+0

希望它有幫助。你不能這樣做,因爲我說Ajax是異步的,當你在函數結尾返回時,'ret array'不會被設置爲值。希望它有幫助。不要介意將它標記爲正確的答案;) –

+0

對..好吧,我必須弄清楚如何做到這一點。謝謝,並會做:) –