General Question

Perchik's avatar

How can I open a text file in javascript?

Asked by Perchik (4997points) February 19th, 2008

I’m new to javascript and I’m trying to open a text file. Basically I have a list of names in a text file and want to build an array from the file. I can come up with code once I actually open the file, but I cannot for the life of me find information online about opening files. Everything I google turns up results about how to load files on demand, right now this is not an issue. Any advice on how to do this, or where to go for more information?

Observing members: 0 Composing members: 0

4 Answers

segdeha's avatar

Do you mean open a file from the file system? That’s not possible using JavaScript within web browsers due to security restrictions (imagine if that warez site you “stumbled onto” could access your file system…ouch!), but it is possible within some environments, like Apple’s Dashboard.

Perchik's avatar

No. I have a file on the server in the same directory. It should be something simple, I just can’t find it.

paulc's avatar

You can use XMLHttpRequest to load any remote file but you’ll be limited in how you can parse it in js. This is also more commonly known as AJAX. You may have to adapt the file to be read by the XML parser but if I remember correctly there is a way to get the raw data as a string.

segdeha's avatar

paulc is right. If the file is on the same server, you can read it using XHR and use the responseText property to get at the contents. If you’re a prototype user, it would look like this:

new Ajax.Request(‘myfile.txt’, {
onComplete: function (transport) {
alert(transport.responseText);
}
});

Answer this question

Login

or

Join

to answer.

This question is in the General Section. Responses must be helpful and on-topic.

Your answer will be saved while you login or join.

Have a question? Ask Fluther!

What do you know more about?
or
Knowledge Networking @ Fluther