简体   繁体   English

使用Javascript导入文本文件

[英]Import Text File Using Javascript

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 iself(定义全局数组)中,但这种方法似乎不可持续。

Is there a way to use Javascript to parse a .txt file located in the same directory on the server? 有没有办法使用Javascript来解析位于服务器上同一目录中的.txt文件? I know this question has probably been asked before, but I've only found answers pertaining to accessing system-local text files. 我知道之前可能已经问过这个问题,但我只找到了有关访问系统本地文本文件的答案。

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大的文件。

Use AJAX. 使用AJAX。 I suggest encoding the file in JSON format, rather than plain text. 我建议用JSON格式编码文件,而不是纯文本。 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. 如果使用jQuery,则可以使用$.getJSON('filename.txt')读取文件,并在一次操作中将其解析为Javascript对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM