0

why isn't it working? The ok () method doesn't give me the correct object. But when I use buttons to activate the methods one by one then it works. Even if I write "await" in front of the getdata () method. It doesn't work.

<script> 
   var javaobj = new Object() ;
    
   function ok(){
      console.log(javaobj);
    }

    function getdata()
    {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function () {
        if (xhttp.readyState==4 && xhttp.status==200) {
          javaobj=JSON.parse(xhttp.response);
        }
      }
      xhttp.open("GET", "test.json", true);
      xhttp.send();
    }
  getdata()
  ok()
</script>

Rayno LP
  • 23
  • 5
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Ivar Oct 01 '20 at 08:34
  • 1
    It works from a button because by the time you click the button, the *asynchronous* request has finished. –  Oct 01 '20 at 08:34
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) –  Oct 01 '20 at 08:35

0 Answers0