-2

Say I have the following code:

<div id="dashboard">
  Loading Dashboard.....
</div>
<script>
  var xhttpDashboard = new XMLHttpRequest();
  xhttpDashboard.onreadystatechange = function() {
    if (xhttpDashboard.readyState == 4 && xhttpDashboard.status == 200) {
      document.getElementById("dashboard").innerHTML = xhttpDashboard.responseText;
    }
  };
  xhttpDashboard.open("GET", "https://www.example.com/getdashboard.html", true);
  xhttpDashboard.send();
</script>

getdashboard.html returns html which in turn contains more javascript XMLHttpRequest to be executed. I am finding these 2nd sets of XMLHttpRequests are not executing.

How can I get the 2nd set of javascript to execute?

Update Found this article to be useful: https://24ways.org/2005/have-your-dom-and-script-it-too

M Schenkel
  • 6,294
  • 12
  • 62
  • 107
  • 3
    Generally, javascript in content gotten with ajax isn't executed. – adeneo Feb 17 '16 at 17:46
  • Is it necessary to get the whole HTML file or are you really just trying to get the Javascript within the HTML file? – HaulinOats Feb 17 '16 at 18:06
  • The script needs to be evaluated (`eval()`). See http://stackoverflow.com/questions/1197575/can-scripts-be-inserted-with-innerhtml. – jtrumbull Feb 17 '16 at 18:14
  • Can you provide a full code. You can't give us only part of the code, especially when the error is in a different part, and expect an answer – Dustin Poissant Feb 17 '16 at 18:19

1 Answers1

0

There is a simple answer if you use jQuery.

When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed.

So with jQuery you could simply do:

<div id="dashboard">
  Loading Dashboard.....
</div>
<script>
$("#dashboard").load("https://www.example.com/getdashboard.html");
</script>

and the script tags would be executed.

The documentation of this function is located here: https://api.jquery.com/load/

jfl1977
  • 16
  • 3