2011-03-25 84 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和瀏覽器端緩存可能會有所幫助。