简体   繁体   中英

AJAX can't load JavaScript in another page

Why can't AJAX load another HTML page with JavaScript? It loads HTML,CSS,PHP etc... but not JavaScript. Is AJAX supposed to work like that? If so how can I load another HTML page that contains JS with AJAX?

A simple example what I mean

a.php

<!DOCTYPE html>
<html>
<body>

<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "b.php", true);
  xhttp.send();
}
</script>

</body>
</html>

b.php

<!DOCTYPE html>
<html>
<body>
<h1>b</h1>
<script>
document.write("Hello World!");
</script>

</body>
</html>

Screenshot of response:
AJAX响应屏幕截图

Because the javascript code you'll get via ajax is a simple string and not executed. You have to eval() the code in the script tag like:

Example:

<script id="helloworld">
document.write("Hello World!");
</script>

JS:

var jsCode = document.getElementById('helloworld').textContent;
eval(jsCode);

Edit by request:

if (this.readyState == 4 && this.status == 200) {
    var demoElement = document.getElementById("demo");
    demoElement.innerHTML = this.responseText;
    var scriptTags = demoElement.getElementsByTagName('script');

    for(i = 0; i < scriptTags.length; i++) {
        eval(scriptTag[i].textContent);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM