简体   繁体   English

AJAX无法在其他页面中加载JavaScript

[英]AJAX can't load JavaScript in another page

Why can't AJAX load another HTML page with JavaScript? 为什么AJAX无法使用JavaScript加载另一个HTML页面? It loads HTML,CSS,PHP etc... but not JavaScript. 它加载HTML,CSS,PHP等...但不加载JavaScript。 Is AJAX supposed to work like that? AJAX应该这样工作吗? If so how can I load another HTML page that contains JS with AJAX? 如果是这样,我如何加载另一个包含JS和AJAX的HTML页面?

A simple example what I mean 一个简单的例子,我的意思是

a.php 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 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. 由于您将通过ajax获取的javascript代码是一个简单的字符串,因此不会执行。 You have to eval() the code in the script tag like: 您必须eval()脚本标签中的代码,例如:

Example: 例:

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

JS: 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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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