problems retrieving "Answer" from a request

Asked

Viewed 34 times

0

I make the request normally, but when trying to recover the response of this request there is no return

let rqs = new XMLHttpRequest();
rqs.open("GET", "https://servicodados.ibge.gov.br/api/v1/localidades/distritos");
rqs.send();
let dados = rqs.responseText;
console.log(dados);
  • Ajax is asynchronous, which means that when line 4 is executed, the request hasn’t even left your computer ( the answer will only arrive a few milliseconds later) and therefore the rqs.responseText variable is null (or undefined). Hence the use of callback onreadystatechange, for your script to be warned of when the answer comes.

2 answers

2

Try this:

let rqs = new XMLHttpRequest();

rqs.onreadystatechange = function() {
    if (rqs.readyState == XMLHttpRequest.DONE) {
        console.log(rqs.responseText);
    }
}

rqs.open("GET", "https://servicodados.ibge.gov.br/api/v1/localidades/distritos");
rqs.send();

  • Why "open" and "send" after the instantiation of the object? see also a lot, after the instantiation, the logic of the script and dpois if it sends the request, it interferes in something?

2

You can do it that way too:

async function getData() {
        const response = await fetch("https://servicodados.ibge.gov.br/api/v1/localidades/distritos");
        const data = await response.json(response);
        console.log(data);
    }
    getData();

The answer will come in JSON, to manipulate you can use the function map or other you want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.