I am trying to get text from a .txt file, with Javascript. I am trying to test my code by using an alert statement to display the text from the file.
I am getting this alert box:
Here is my code:
$(document).ready(function() {
// Obtain services text from .txt file
var text = new XMLHttpRequest();
text.open("GET", "js/servText.txt", true);
text.onreadystatechange = function() {
// Check states 4 = Ready to parse, 200 = found file
if(text.readyState === 4 && text.readyState === 200) {
text = text.responseText;
}
}
alert(text);
text.send(null);
});
I have tried to use JSON.stringify(); but I got an alert box with '{}' and it did not work in Google Chrome.
I also tried to use toString(); and String();
Any help would be great! Thanks -Chris
I am trying to get text from a .txt file, with Javascript. I am trying to test my code by using an alert statement to display the text from the file.
I am getting this alert box:
Here is my code:
$(document).ready(function() {
// Obtain services text from .txt file
var text = new XMLHttpRequest();
text.open("GET", "js/servText.txt", true);
text.onreadystatechange = function() {
// Check states 4 = Ready to parse, 200 = found file
if(text.readyState === 4 && text.readyState === 200) {
text = text.responseText;
}
}
alert(text);
text.send(null);
});
I have tried to use JSON.stringify(); but I got an alert box with '{}' and it did not work in Google Chrome.
I also tried to use toString(); and String();
Any help would be great! Thanks -Chris
Share Improve this question asked Apr 19, 2013 at 16:29 Chris FrankChris Frank 4,4824 gold badges32 silver badges43 bronze badges1 Answer
Reset to default 3You need to move your alert
statement into the callback.:
$(document).ready(function() {
// Obtain services text from .txt file
var text = new XMLHttpRequest();
text.open("GET", "js/servText.txt", true);
text.onreadystatechange = function() {
// Check states 4 = Ready to parse, 200 = found file
if(text.readyState === 4 && text.status === 200) {
alert(text.responseText);
}
}
text.send(null);
});
AJAX calls are, as the name implies, Asynchronous. Your alert
gets called immediatly, it doesn't wait for the AJAX request to plete.
Asynchronousness can be quite a mind boggle. Your code doesn't run from top to bottom but rather you have to look at the events. Where does an event start? what data do I have? etc.