【发布时间】:2014-02-18 15:21:29
【问题描述】:
使用 Ajax,我正在调用一个包含 javascript 的 php 文件,但是这样,javaScript 不起作用。
这里给出了 main.html 文件。它只是使用 Ajax 调用一个名为 test1.php 的 php 文件来更新客户端的所有页面。
<!DOCTYPE html>
<html>
<body>
<!-- run php file to fill the page -->
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.body.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","test1.php",true);
xmlhttp.send();
</script>
</body>
</html>
而test1.php文件很简单,测试如下:
<p id="demo">Hi there</p>
<script>
document.write("Yes! Hi there");
alert('Welcome!');
</script>
现在,只是为了检查 test1.php 是否正常,我输入了浏览器的 url 行:
localhost/test1.php
一切正常,显示 html 和 js 的文本,并出现一个带有“欢迎”字样的警告窗口!显示出来。
但是如果我调用主页
localhost/main.html
然后只显示html文本'Hi there'。 JS 被忽略。
有人知道这是为什么吗? 谢谢
【问题讨论】:
-
它应该与附加一起工作,而不是将其提供给 innerHTML。 Append 会将其附加为 HTML,并且应该执行 js。 Quentin 是对的,该线程有解决方案。
标签: javascript php ajax