I'm trying to use this function to return as a global variable a String
object that is the contents of a local text file. Right now it is returning an empty String
.
function get_words()
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "wordsEn.txt", true);
var allText = new String();
rawFile.onreadystatechange = function ()
{
if (rawFile.readyState === 4)
{
if (rawFile.status === 200 || rawFile.status == 0)
{
allText = rawFile.responseText;
}
}
}
rawFile.send(null);
return allText;
}
However, when I change the body of the second if statement to
allText = rawFile.responseText;
alert(allText);
I do get an alert
message that is the correct contents of the text file.
However, when I instead put the alert
message right before the return
statement, I get an empty alert
message.
I would be happy if you could give me some insight on the behavior here and possibly help me fix it to accomplish the task of returning as a string the contents of the text file. Thanks in advance.