简体   繁体   English

如何将数据从文本文件加载到javascript中的变量中

[英]How do you load data from a text file into a variable in javascript

I'm just trying to do something that simple. 我只是想做些简单的事情。 All I want to do is load the contents of a text file into a variable. 我要做的就是将文本文件的内容加载到变量中。 The text file is only one line and is always a string. 文本文件只有一行,并且始终是一个字符串。 I know there are other threads asking the same question, but as of now, the closest answer I have gotten is this: 我知道还有其他线程在问同样的问题,但是到目前为止,我得到的最接近的答案是:

var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
   alert(client.responseText);
}
client.send();

The problem with this is that I am trying to load the information into a variable. 问题是我正在尝试将信息加载到变量中。 Not send it as an alert. 不发送它作为警报。 I have tried this: 我已经试过了:

var string;
var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
   string = client.responseText;
}
client.send();

This does not work either. 这也不起作用。

This is not a duplicate of this post , as that post is focused on Ajax, and doesn't actually answer how to import the information. 这不是此文章的重复内容,因为该文章专注于Ajax,实际上并未回答如何导入信息。 I'm not utilizing Ajax. 我没有使用Ajax。 I want the information from the file to be usable elsewhere in the program. 我希望文件中的信息在程序的其他地方可用。

it is evident that you are trying to make an HTTP request to the user's local computer and for obvious reasons - browsers do not allow this! 很明显,您正在尝试向用户的本地计算机发出HTTP请求,并且出于明显的原因-浏览器不允许这样做! else hackers would be able to read the entire content of a users C drive if they wanted - or worse! 否则,黑客将可以读取用户C驱动器的全部内容,甚至更糟!

So - you are required to upload the file! 所以-您需要上传文件! ie <input type="file" id="uploadFile" /> Check this JSFiddle , you would use the onChange event of the input to read the file <input type="file" id="uploadFile" />选中此JSFiddle ,您将使用onChange event of the input to read the fileonChange event of the input to read the file

For a similar situation, I used file upload to the server and used PHP/c# (cant remember off the top of my head) which returned the required data - this made things a bit easier actually - the server would receive the file and validate, extract required information and return just the required data - although it seems like more work on the server side - which it is a little bit more you can plan it to make reduce the amount of javascript code you might have to write. 在类似情况下,我使用文件上传到服务器,并使用PHP / c#(想不起来了)返回了所需的数据-这实际上使事情变得容易一些-服务器将接收文件并进行验证,提取所需的信息并仅返回所需的数据-尽管在服务器端似乎需要更多工作-您可以对其进行一些规划,以减少可能需要编写的javascript代码量。

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

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