Panzercrisis
Panzercrisis

Reputation: 4750

What is the simplest way you can read from a file in JavaScript?

I know this question has asked before, but I'm still learning JavaScript, and I'm having trouble seeing through the complexity of other people's answers. I have a text file in the same directory as an HTML file that's reading JavaScript, and that text file literally has one line in it. I want to be able to grab that line out of the text file and put it in a string. What's a really simple way to do this that'll work in FF, IE, and Chrome, and is, aside from browser choice, is fairly universally valid? Again, I know this has been asked before, but I'm having trouble picking the real method here out of the complexity of example code I've seen elsewhere. Thanks!

Upvotes: 0

Views: 219

Answers (3)

momo
momo

Reputation: 21353

Use jQuery get method http://api.jquery.com/jQuery.get/

$.get(url).success(function(data, status, response) {
    var text = response.responseText;
    // use your one line text stored in text variable here
}

The url variable can be relative, so you could put the text filename there. For example if your text file is called "mytext.txt" and in the same directory of the script accessing it you put:

  $.get("mytext.txt").success(function(data, status, response) {
        var text = response.responseText;
        // use your one line text stored in text variable here
    }

Note this answer assumes you are using http to access the text file and both script and text file is in the same domain.

Upvotes: 3

Jeffrey Sweeney
Jeffrey Sweeney

Reputation: 6124

The simplest way I can think of is to use a server-sided language to output the contents of the document into the page somewhere (such as an invisible textarea), and just have Javascript read that. No AJAX, no libraries, and it's really fast.

<textarea id="textarea"><?php include("test.txt") ?></textarea>

<script>
var str = document.getElementById("textarea").value;
</script>

Now, this isn't always the best way, but compared to using asynchronous Javascript everywhere with heavy frameworks at the expense of SEO performance...

Upvotes: 1

Hippocrates
Hippocrates

Reputation: 2540

This is tricky because most browsers by default do not permit JS to open files locally from the computer's file system. You can request the text file from a web server using ajax though. To do this I would recommend jQuery as it will be very "universally valid" as you put it. When doing ajax calls, the request must adhere to the same origin policy. In laymans terms, if you are at www.mysite.com you can request www.mysite.com/aTextFile.txt but you would not be able to request www.someothersite.com/aTextFile.txt

To do this with jquery, see momo's answer. I was going to type the same thing but he/she beat me to it.

Upvotes: 2

Related Questions