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?

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

10 Comments

That's working now, but the JS still isn't coming in.
The JS inside of form.html isn't being loaded.
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? stackoverflow.com/questions/2592092/…
Yeah form.html has a bunch of <script src="file.js"></script> in it.
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 <script> tags
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.