2011-03-25 81 views
1

我正在使用AJAX从文本文件中读取数据。我如何只读第一行?从文件中读取AJAX

+0

还我如何检测是否文本文件改变了吗?我不想要使用setTimeout并每200ms检查一次文件-_- – WindowsMaker 2011-03-25 19:56:00

回答

5

此代码应帮助你从远程文本文件阅读:

var txtFile = new XMLHttpRequest(); 
txtFile.open("GET", "http://my.remote.url/myremotefile.txt", true); 
txtFile.onreadystatechange = function() { 
    if (txtFile.readyState === 4) { // Makes sure the document is ready to parse. 
    if (txtFile.status === 200) { // Makes sure it's found the file. 
     allText = txtFile.responseText; 
     lines = txtFile.responseText.split("\n"); // Will separate each line into an array 
    } 
    } 
} 
txtFile.send(null); 
+1

thx!很棒! – WindowsMaker 2011-03-25 20:18:34

+0

真棒!!!!! ;) – 2011-03-29 17:41:12

0

这取决于您如何在后端输出文件。根据不同的语言,无论是PHP,Java还是其他语言,都可以读取文件的第一行并将其输出到响应中。

要找出文件是否已更改:在这种情况下,HTTP代码304和浏览器端缓存可能会有所帮助。