2015-02-06 126 views
-2

這裏財產「0」是我的腳本:遺漏的類型錯誤:無法讀取的不確定

<script> 
var count; 
var obj; 

function recherche() { 
    xhr = new XMLHttpRequest(); 
    xhr.open("GET", "test.json", true); 
    xhr.send(null); 
    xhr.onreadystatechange = function() { 
     if (xhr.readyState == 4 && xhr.status == 200) { 
      var res = xhr.responseText; 
      obj = JSON.parse(res); 

      for (count = 0; count < obj.length; count++) { 
       alert(obj[count].humidity); 
      } 
     } 

    } 

} 
          alert(obj); 

window.onload = recherche; 
</script> 

我有這樣的錯誤運行此腳本後:

Uncaught TypeError: Cannot read property '0' of undefined 

第一個警報工作正常顯示我20 ,30,40,但如果我做了外界的警報,我有undefined。

我想使用obj對象來使用從json文件存儲的數據作爲數據在腳本中進一步繪製圖表,但這個錯誤會彈出。

我做錯了什麼?

回答

1

默認情況下,XHR請求是異步。這意味着send開始他們,但他們稍後完成(這就是爲什麼他們有回調,而不是返回值)。只需在回調中使用obj即可。


邊注:您的代碼墮入The Horror of Implicit Globals(你永遠不會宣佈你xhr變量)。

+0

但我需要在以後的另一個函數obj:/ – 2015-02-06 23:50:27

+0

@YoussefKamoun:然後你從回調調用該函數。 – 2015-02-07 08:34:09

相關問題