2015-02-06 60 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

相关问题