0

my scriptedHTTP.js has:

  var req = new XMLHttpRequest();
  req.open("GET", "scripts/text.txt", true);
  req.send(null);
  var div = document.createElement('div');
  div.innerHTML = req.responseText;

when I load the page, browser console shows:

  XHR finished loading: GET "http://localhost:8000/scripts/text.txt".

but I get nothing on the page:

how do I handle responseText so it shows on the page?

thanks.

8-Bit Borges
  • 9,643
  • 29
  • 101
  • 198

1 Answers1

1

Ajax is asynchronous. req.responseText only it works when the load is performed successfully. You must use the req.onreadystatechange that is triggered when the load status has changed, so now you can use req.responseText

  req.onreadystatechange = function(){
     if(req.readyState == 4 && req.status == 200){
        div.innerHTML = req.responseText;
     }
  };
Community
  • 1
  • 1
  • place it after `var req = new XMLHttpRequest ();`, I recommend you go to the [link](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) so you know more about it – Walter Chapilliquen - wZVanG Jun 27 '15 at 05:19