How can I declare a .txt file as a string?
I have a text file whose Unicode chara开发者_JAVA百科cters 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?
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.
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.
As best I know, you would have to use an ajax call to read the file into a string.
You can use XmlHttpRequest, jquery or AJAX to read the text file using its URL, then parse the response.
The issue here was the problem. Upon making the request synchronous, I was able to define t
in line with my script.
精彩评论