I want to put the text of a .txt in a variable. I have found the following code:
var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
alert(client.responseText);
}
client.send();
Now I modify it as follows:
var client = new XMLHttpRequest();
var chaintext = client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
alert(client.responseText);
}
client.send();
console.log(chaintext);
I create a .txt with a phrase in the folder C:\Users\USER\Downloads
But nothing... The console tells me "undefined". I suppose that there are several things that may be failing: to begin with, the path is wrong or the directory to which the browser is pointing is something else. Does anyone know how I can write a code that opens a .txt from a specific path?
The XMLHttpRequest object reacts to various events. Your code listens for the event
readystatechange
, which means that the variablereadyState
has varied .That the state changes does not always mean that the file has been uploaded, because all errors (HTTP status 4XX/5XX) also cause a change of the readyState.
Therefore, to know what is happening you could do something like:
Another option (unless you have to support very old browsers) is to use
fetch
: