使用javascript逐行读取本地文件

时间:2015-11-13 08:13:19

标签: javascript jquery

我试图完成以下任务:

  • 逐行阅读文件
  • 每行拆分
  • 创建动态行,每个单词作为列。

我尝试了类似下面的内容,但它无效:

$.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');

2 个答案:

答案 0 :(得分:1)

确保您拥有included jQuery before your code executes,并在文档中使用table元素并使用正确的id值,如下所示:

<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 |                                 |

答案 1 :(得分:0)

您必须先设置<input type="file" id="myfile" />才能操作文件。

然后用(jquery)获取你的文件:

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

否则你无法访问它。