简体   繁体   中英

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. I'm not utilizing 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! else hackers would be able to read the entire content of a users C drive if they wanted - or worse!

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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