如何使用 JavaScript 从服务器读取文本文件? [英] How to read a text file from server using JavaScript?

查看:75
本文介绍了如何使用 JavaScript 从服务器读取文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在服务器上,有一个文本文件.在客户端使用 JavaScript,我希望能够读取此文件并对其进行处理.无法更改服务器上文件的格式.

On the server, there is a text file. Using JavaScript on the client, I want to be able to read this file and process it. The format of the file on the server cannot be changed.

如何将文件内容放入 JavaScript 变量中,以便进行此处理?文件的大小最多可达 3.5 MB,但可以轻松地以 100 行(1 行是 50-100 个字符)为单位进行处理.

How can I get the contents of the file into JavaScript variables, so I can do this processing? The size of the file can be up to 3.5 MB, but it could easily be processed in chunks of, say, 100 lines (1 line is 50-100 chars).

文件的任何内容都不应该对用户可见;他会看到文件中数据的处理结果.

None of the contents of the file should be visible to the user; he will see the results of the processing of the data in the file.

推荐答案

您可以使用隐藏框架,在其中加载文件并解析其内容.

You can use hidden frame, load the file in there and parse its contents.

HTML:

<iframe id="frmFile" src="test.txt" onload="LoadFile();" style="display: none;"></iframe>

JavaScript:

JavaScript:

<script type="text/javascript">
function LoadFile() {
    var oFrame = document.getElementById("frmFile");
    var strRawContents = oFrame.contentWindow.document.body.childNodes[0].innerHTML;
    while (strRawContents.indexOf("
") >= 0)
        strRawContents = strRawContents.replace("
", "");
    var arrLines = strRawContents.split("
");
    alert("File " + oFrame.src + " has " + arrLines.length + " lines");
    for (var i = 0; i < arrLines.length; i++) {
        var curLine = arrLines[i];
        alert("Line #" + (i + 1) + " is: '" + curLine + "'");
    }
}
</script>

注意:为了使其在 Chrome 浏览器中工作,您应该使用 --allow-file-access-from-files 标志启动它.信用.

Note: in order for this to work in Chrome browser, you should start it with the --allow-file-access-from-files flag. credit.

这篇关于如何使用 JavaScript 从服务器读取文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆