Load .txt file from javascript with jquery

13,920

Solution 1

by default javascript is NOT allowed to access local file system for security reasons. If you want to allow a particular script access to a local file then you have 2 options.

1a. Change your model, put the text file on a server and load from there...

1b. Run a local webserver :-)

2 ... this becomes browser dependent,

In particular,

Solution 2

You can't, place it on a web server (on the same domain you are working on) then perform an AJAX GET.

var file = (function func1() {
    var result;

    $.ajax({
        type: "GET",
        url: file,
        async: false,
        success: function(data){
            result = data;
        }
    });
    return result;
})();

Solution 3

I'm guessing by your question that maybe you're trying to do some form of JS templating. In which case, you'd probably want to look at something like this: http://github.com/andyet/icanhaz.js

The short of it is, you can store text that you want access to in JS in this way:

<script id="my_snippet" type="text/html">
    Whatever random text here, format doesn't really matter,
    you can use whatever unless  you're trying to serve it as xml.
</script>

It's actually valid in HTML 5. Then you can retrieve the contents in JS like so:

$('#my_snippet').html();

ICanHaz.js abstracts this all a bit for you so if you're templating... I'd recommend using that instead.

Share:
13,920

Related videos on Youtube

Luccas
Author by

Luccas

Updated on June 04, 2022

Comments

  • Luccas
    Luccas almost 2 years

    I want to load a local .txt file and work with the content in javascript. My local file is like C:\Users\Who\Desktop\file.txt Thanks

    • mk12
      mk12 almost 14 years
    • Luccas
      Luccas almost 14 years
      i've seen it. but i want to get ir from my computer directly. jQuery.get('file://C:/Users/Luccas/Desktop/idades.txt', function(data) { var myvar = data; }); seems not to work, only solution to place on server to get via ajax said under.
    • Doug Molineux
      Doug Molineux almost 14 years
      @Yacoby, perhaps he needs some advice/pointers?? An unfriendly response like this really steers people away from sites like this
  • µBio
    µBio almost 14 years
    Not really true. You can't load the text from file using javascript, but you could certainly get it to the javascript for processing. See my answer.
  • Anders
    Anders almost 14 years
    Yes, you can use a number of back end solutions, I answered the question in the context of JavaScript, a client based solution,