Home > Enterprise >  I want to put a responseText value in a variable in browser
I want to put a responseText value in a variable in browser

Time:01-19

let xhr = new XMLHttpRequest();

xhr.open("GET", "https://reqbin.com/echo/get/json");

xhr.onreadystatechange = () => {
  if (xhr.readyState === 4) {
    console.log(xhr.responseText);
  }
};

xhr.send();
let a = xhr.responseText

Why can't I save the value of variable 'a' right away?

I can not get the value {"success":"true"}

how can i get?

CodePudding user response:

Since this request is happening asynchronously your

let a = xhr.responseText

code is executing before the server returns a response

In that case what you can do is place the code that you want to execute inside onreadystatechange event handler, which will execute after server has returned you a response.

let xhr = new XMLHttpRequest();
let a;
xhr.open("GET", "https://reqbin.com/echo/get/json");

xhr.onreadystatechange = () => {
  if (xhr.readyState === 4) {
    console.log(xhr.responseText);
    a = xhr.responseText
  }
};

xhr.send();

  • Related