Specifying a path to load a .txt with javascript

1

I want to put the text of a .txt in a variable. I found the following code:

var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
  alert(client.responseText);
}
client.send();

Now I am modifying 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 says "undefined." I suppose there are several things that may be failing: to start the route is wrong or the directory to which the browser is pointing is another. Does anyone know how I can write a code that opens a .txt of a specific route?

    
asked by Mr. Baldan 22.10.2018 в 14:02
source

1 answer

1

The XMLHttpRequest object reacts to several events. Your code listens to the readystatechange event, which means that the variable readyState has varied .

That the state changes does not always mean that the file has been loaded, because all the errors (HTTP status 4XX / 5XX) also cause a change of the readyState.

Therefore, to know what is happening you could do something like:

client.onreadystatechange = function() {
  console.log('Respuesta recibida');
  console.log('HTTP status',client.status);
  if (client.status === 200) { // OK
    console.log('Respuesta:',client.responseText);
  } else {
    console.log('Error:',client.statusText);
}

Another option (unless you have to support very old browsers) is to use fetch :

// fetch no considera una respuesta distinta a 200 un "error",
// esta función lanza el error si la eespuesta no es HTTP 200 OK
function handleErrors(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
}

let responseProm = fetch('/foo.txt'); // Devuelve una Promise
responseProm
  .then(handleErrors)
  .then(resp => resp.text()).
  .then(text => console.log('El texto es:', text))
  .catch(err => console.log('Error:',err);
    
answered by 22.10.2018 / 15:21
source