Isaac Lubow
Isaac Lubow

Reputation: 3573

How can I declare a .txt file as a string?

I have a text file whose Unicode characters I'd like to read one-by-one using charCodeAt(). Is there syntax I can use to declare the contents of the file as a string by specifying the URL of the text file?

EDIT: I have the following code using jQuery as recommended below:

var t;
var music = function(source){
        $.get(source, function(data){
        t = data;
    });
}
music('music.txt');
alert(t.length);

But the alert is presently undefined. What am I missing?

Upvotes: 0

Views: 185

Answers (5)

HelperUDI
HelperUDI

Reputation: 41

Use $. Ajax instead of $. Get, so you can configure the call to the asynchronous mode (async: false), this will force the browser to wait for the execution of AJAX call before continuing processing.

Note the jquery documentation: "Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active."

var t;

var music = function(){
    $.ajax({
        async: false,
        url: "/music.txt", 
        dataType: "text", 
        sucess: function(data){
            alert(data);
            t = data;
        }
    });
};
music("music.txt");
alert(t.length);

Thanks.

Upvotes: 2

Isaac Lubow
Isaac Lubow

Reputation: 3573

The issue here was the problem. Upon making the request synchronous, I was able to define t in line with my script.

Upvotes: 0

Quentin
Quentin

Reputation: 943569

You can use XMLHttpRequest and, when loaded, the data will appear in responseText.

Browser variations mean it is a good idea to use a library.

Upvotes: 1

mohammedn
mohammedn

Reputation: 2950

You can use XmlHttpRequest, jquery or AJAX to read the text file using its URL, then parse the response.

Upvotes: 0

jfriend00
jfriend00

Reputation: 707366

As best I know, you would have to use an ajax call to read the file into a string.

Upvotes: 1

Related Questions