使用 Javascript 导入文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18366191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:39:20  来源:igfitidea点击:

Import Text File Using Javascript

javascripthtmltextimport

提问by Michael Hang

I am currently working on an application that handles a fairly large amount of data. Currently, I've hard-coded those values into the Javascript iself (defining global arrays), but this method does not seem sustainable.

我目前正在开发一个处理相当大量数据的应用程序。目前,我已将这些值硬编码到 Javascript 本身(定义全局数组)中,但这种方法似乎不可持续。

Is there a way to use Javascript to parse a .txt file located in the same directory on the server? I know this question has probably been asked before, but I've only found answers pertaining to accessing system-local text files.

有没有办法使用 Javascript 来解析位于服务器上同一目录中的 .txt 文件?我知道之前可能有人问过这个问题,但我只找到了与访问系统本地文本文件有关的答案。

采纳答案by Barmar

Use AJAX. I suggest encoding the file in JSON format, rather than plain text. If you use jQuery, you can then use $.getJSON('filename.txt')to read the file and parse it into a Javascript object in one operation.

使用 AJAX。我建议以 JSON 格式编码文件,而不是纯文本。如果您使用 jQuery,那么您可以使用$.getJSON('filename.txt')读取文件并将其解析为一个操作中的 Javascript 对象。

回答by cocco

Here is native javascript solution without libraries.

这是没有库的原生 javascript 解决方案。

http://caniuse.com/xhr2

http://caniuse.com/xhr2

As it's async you have to create 2 functions

由于它是异步的,因此您必须创建 2 个函数

one to read and another one to show/modify or whatever

一个阅读,另一个显示/修改或其他

function read(textFile){
    var xhr=new XMLHttpRequest;
    xhr.open('GET',textFile);
    xhr.onload=show;
    xhr.send()
}

function show(){
    var pre=document.createElement('pre');
    pre.textContent=this.response;
    document.body.appendChild(pre)
}

read('text.txt');

if you work alot with external files i suggest also to take a look at the new javascript classes new FileReader()and window.requestFileSystem()

如果您经常使用外部文件,我还建议您查看新的 javascript 类new FileReader()window.requestFileSystem()

where new FileReader()has now a little more support, also on mobile devices

哪里new FileReader()现在有更多的支持,也在移动设备上

and from what i know window.requestFileSystem()has almost no support.. but you can handle files that are various gb large.. using Chrome.

据我所知window.requestFileSystem()几乎没有支持..但是你可以使用Chrome处理各种gb大的文件..