簡體   English   中英

使用javascript逐行讀取本地文件

[英]Read local file line by line using javascript

我正在嘗試實現以下任務:

  • 逐行讀取文件
  • 在每一行中分割單詞
  • 用每個單詞作為一列創建動態行。

我嘗試了以下操作,但無法正常工作:

$.get('test.txt', function(myContentFile) {
    var lines = myContentFile.split("\r\n");
    var table = document.getElementById("myTableData");

    for(var i  in lines){
        var str = lines[i]
        var res = str.split(",");
        var row = table.insertRow(0);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        cell1.innerHTML = res[0];
        cell2.innerHTML = res[1];
    }

}, 'text');

確保在代碼執行之前包含jQuery ,並在文檔中使用具有正確id值的table元素,如下所示:

<table id="myTableData" border="1"><table>

還要確保您的文本文件( text.txt )與html頁面位於同一本地文件夾中。

如果滿足所有這些條件,則代碼將運行。 不過,到星期幾仍有一些事情。 查看我添加到您的代碼中的更改和注釋:

<html>
<head>
    <meta charset="UTF-8">
    <script src="http://code.jquery.com/jquery-1.9.0.js"></script>
</head>
<body>
<table id="myTableData" border=1><table>

<script type="text/javascript">
    $.get('test.txt', function(myContentFile) {
        console.log(myContentFile);
        // Added: strip ending new-lines from the retrieved text:
        myContentFile = myContentFile.replace(/[\r\n]$/, '');
        // Modified: split lines also when delimited by linefeeds only:
        var lines = myContentFile.split(/\r\n|\n/);
        var table = document.getElementById("myTableData");

        for(var i  in lines){
            var str = lines[i]
            var res = str.split(",");
            // Modified: remove argument to add rows to the end of the table
            var row = table.insertRow();
            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);
            cell1.innerHTML = res[0];
            // Modified: test that second element exists to prevent "undefined" output
            cell2.innerHTML = res[1] ? res[1] : '';
        }
    }, 'text');
</script>
</body>
</html>

我將以下test.txt文件放在同一文件夾中:

This is a test, with something in second column
And a second line, that also has a second column
The third line just has one value

然后,當我在瀏覽器中打開html頁面時,得到以下輸出:

| This is a test                    | with something in second column |
| And a second line                 | that also has a second column   |
| The third line just has one value |                                 |

您必須先放置<input type="file" id="myfile" />然后才能操作文件。

然后使用(jquery)獲取文件:

var myFile = $('#myfile').prop('files');

否則,您將無法訪問它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM