[英]AJAX can't load JavaScript in another page
为什么AJAX无法使用JavaScript加载另一个HTML页面? 它加载HTML,CSS,PHP等...但不加载JavaScript。 AJAX应该这样工作吗? 如果是这样,我如何加载另一个包含JS和AJAX的HTML页面?
一个简单的例子,我的意思是
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>
响应的屏幕截图:
由于您将通过ajax获取的javascript代码是一个简单的字符串,因此不会执行。 您必须eval()脚本标签中的代码,例如:
例:
<script id="helloworld">
document.write("Hello World!");
</script>
JS:
var jsCode = document.getElementById('helloworld').textContent;
eval(jsCode);
根据要求编辑:
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.