2011-04-01 46 views
3

我有文件main.log是這樣的:線陣列

10-01-1970 01:42:52 Bus_Power device 9 up 
10-01-1970 01:42:52 External_Power device 9 up 
10-01-1970 01:42:57 Bus_Power device 1 down 
10-01-1970 01:42:57 Bus_Power device 2 down 

每一行是一個數據。如何使用Dojo或純JavaScript解析這些行數組?

例如:

['10-01-1970 01:42:52 Bus_Power device 9 up','10-01-1970 01:42:52 External_Power device 9 up'] 

回答

3

如果你有文件轉換成字符串(比如「文本」),那麼你可以做:

var lines = text.split("\n"); 

檢查,如果你的服務器上的文件結束只用一個換行線(UNIX風格)或CR-LF對(Windows風格)。

如何將文件轉換爲字符串?您可以使用dojo.xhrGet(...)。在Dojo文檔中查找它。

4
var xhr = new XMLHttpRequest(); 

xhr.open('GET', 'main.log', false); 
xhr.send(null); 

var log = xhr.responseText.split('\n'); 

// `log` is the array of logs you want 

注:同步,完成,爲簡單起見沒有透露具體細節給出關於此功能的應用程序。

+0

注意事項:dojo將有一個很好的AJAX組件,您應該使用,而不是從庫中受益。 – Chris 2011-04-01 08:02:47

+0

+1也許可以使用'xhr.responseText.split(/ \ r?\ n /);'替代?或者這是不必要的? (我不確定)。 – 2011-04-01 08:04:32

1

假設你正在閱讀文本/日誌文件,下面的代碼是從stackflow.com的another post修改,

var contentType = "application/x-www-form-urlencoded; charset=utf-8"; 

var request = new XMLHttpRequest(); 
request.open("GET", 'test.log', false); 
request.setRequestHeader('Content-type', contentType); 

if (request.overrideMimeType) request.overrideMimeType(contentType); 

// exception handling 
try { request.send(null); } catch (e) { return null; } 
if (request.status == 500 || request.status == 404 || request.status == 2 || (request.status == 0 && request.responseText == '')) return null; 

lines = request.responseText.split('\n') 
for(var i in lines) { 
    console.log(lines[i]); 
} 

問題可能是由編碼/解碼的問題引起的,所以我們可能需要異常處理以及。有關XMLHttpRequest的更多信息,請訪問here