2014-10-31 56 views
-1

下面的代码显示应该从temps.txt文件导入值 ,但时间数组 显示为空,可能是错误的?从数据文件导入数组

我只得到“Nan”作为输出。

的temps.txt文件看起来是这样的:

21.5 
22.3 
... etc 

这里是我的源代码:

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8"> 
    <title>load demo</title> 
    <style> 
    body { 
    font-size: 16px; 
    font-family: Arial; 
    } 
    </style> 
    <script src="//code.jquery.com/jquery-1.10.2.js"></script> 
</head> 
<body> 

<script> 
var times = []; 

$.get('temps.txt', function(data) { 
    times = data.split("\n"); 
    }); 
for (var i in times) 
{ 
    document.write(times[i] + "<BR />"); 
} 

</script> 
</html> 
+3

$ .get是一个异步调用,你的for循环应该在回调函数内部,在times = data.split(“\ n”)之后。 – lshettyl 2014-10-31 16:23:47

+1

另外,不要使用'document.write'。它会在每次使用文档时替换文档上的所有内容。使用jQuery创建一个元素并将其他元素附加到它。 – Andy 2014-10-31 16:24:14

+0

我想保持数据在时间数组或不可能? – tubos 2014-10-31 16:27:13

回答

0

事情是这样的:

1)将循环到$.get回调。

2)使用一个数组来建立你的字符串

3)它追加到使用join主体元件。

$.get('temps.txt', function(data) { 
    times = data.split("\n"); 
    var html = []; 
    for (var i in times) { 
    html.push(times[i] + '<br/>'); 
    } 
    $('body').append(html.join('')); 
});