1

I've written the snippet below to send an HTTP request to get an HTML file. The HTML file has CSS and JS included (link and script tags):

var request = new XMLHttpRequest();
request.open('GET', 'form.html', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    var resp = request.responseText;

    this.innerHTML = resp;
  } else {

  }
};

request.onerror = function() {

};

request.send();

The above snippet sends a request and gets the HTML. However, it's having problems putting the HTML into the DOM and it's not sending requests to fetch the styles and javascript. How can I do the above and take the response HTML, put it into the page, and have it send the requests to get the various assets?

Noah
  • 874
  • 7
  • 11

1 Answers1

1

In your onload handler, this refers to the request object, not the document, so setting the innerHTML property won't do anything useful. You need to tell it where to put the new HTML, e.g.

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    var resp = request.responseText;

    document.documentElement.innerHTML=resp;
  } else {

  }
}

(Note this won't work in early IE versions)

CupawnTae
  • 14,192
  • 3
  • 29
  • 60
  • That's working now, but the JS still isn't coming in. – Noah Aug 31 '15 at 16:11
  • The JS inside of `form.html` isn't being loaded. – Noah Aug 31 '15 at 16:23
  • You mean inline script is not being executed? Yeah, that won't work - perhaps one of the answers to this question would work for you? http://stackoverflow.com/questions/2592092/executing-script-elements-inserted-with-innerhtml – CupawnTae Aug 31 '15 at 16:31
  • Yeah `form.html` has a bunch of `` in it. – Noah Aug 31 '15 at 16:35
  • Not inline. I used the snippet from that answer, and it's running the inline now. But I ALSO need to make sure it sends the request to get the JS from the ` – Noah Aug 31 '15 at 16:39
  • sorry, on a train with dreadful network coverage at the moment so can't help much - should be possible to find and re-inject the script `src="..."` elements via DOM manipulation to have them load – CupawnTae Aug 31 '15 at 16:48
  • Can you add an example to your answer? – Noah Aug 31 '15 at 17:07
  • Any idea why the code from that answer is working for inline script tags, but not ones with an `src` attribute? – Noah Aug 31 '15 at 17:12
  • Apologies, just back to netland now. I presume you used the accepted answer? There's one further down that deals with `src` attributes - here: http://stackoverflow.com/a/26716182/1469259 - let me know if that works, and if so I'll edit it into the answer. – CupawnTae Aug 31 '15 at 18:35
  • (and the reason is that the accepted answer doesn't copy the `src` attribute to the newly-created `script` element, so if you prefer to stick with the more elaborate script you should be able to just add `script.src = elem.src` after `script` is created to get it to work) – CupawnTae Aug 31 '15 at 18:39