为什么使用AJAX返回的Javascript代码不会写入指定的<div>,但它会替换整个页面?

Cal*_*oiu 2 javascript php ajax jquery

我正在使用AJAX(使用jQuery)请求一个包含对Apache + PHP服务器的Javascript函数调用的标记.这是HTML和AJAX代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://localhost/LivingLab/javascript/jquery.min.js"></script>
</head>

<body>
<a href="javascript: void(0)" onclick="
    $.post(
        'http://localhost/test.php',    // server target page
        {some_var: 'abc'},              // data to be sent via POST method
        function(data) {                // JS callback function
            $('#container').html(data); // innerHTML of <div id="container"> will be replaced
        }
    )
">Click me!</a>
<div id="container"></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

AJAX请求页面'http://localhost/test.php',它具有以下PHP代码:

<?php
    echo '<script type="text/javascript"> document.write("Javascript output"); </script>';
?>
Run Code Online (Sandbox Code Playgroud)

当我点击链接时,在AJAX请求之后,整个页面被"Javascript output"替换,而不是仅在id为"container"的div标签内写入.

如果PHP服务器脚本写入其他内容,而不是像这样的脚本标记:

<?php echo 'text' ?>
Run Code Online (Sandbox Code Playgroud)

通过用id"container"替换div而不是整个页面,AJAX调用表现正常.

我试图用Wireshark调查这个页面传输的HTTP数据,它似乎不是一个HTTP问题,因为服务器响应正是它应该是这样的:

<script type="text/javascript"> document.write("Javascript output"); </script>
Run Code Online (Sandbox Code Playgroud)

在没有AJAX的情况下运行Javascript代码不会替换整个页面,只有在使用AJAX返回脚本标记时才会发生这种情况.注意到在Firefox 3和5以及谷歌浏览器中也有相同的行为.

为什么会这样?

T.J*_*der 9

document.write通常在页面的主要加载期间使用,在此期间它输出到浏览器读取以呈现主页面的解析流.如果在页面的初始加载完成使用它,它会open在文档上隐式执行,它会完全删除文档,并使用新编写的内容重新开始.

简短版本是:仅document.write在主页加载期间使用(如果那样).页面加载后,使用DOM操作.

示例(实时复制):

<body>
  <input type='button' id='theButton' value='Click Me'>
  <script>
    document.write(
      "<p><code>document.write</code> is fine here, during " +
      "the main load of the page.</p>");
    document.getElementById("theButton").onclick = function() {
      document.write(
        "<p>But not here, because the initial " +
         "page load is complete and using " +
         "<code>document.write</code> at this point tears " +
         "down the document and starts  new one.</p>");
    };
  </script>
</body>
Run Code Online (Sandbox Code Playgroud)

有关DOM2 HTML规范,HTML5规范MDC的更多信息:

  • document.write:DOM2 | HTML5 | MDC
  • document.open:DOM2 | HTML5 | MDC
    (document.write如果在加载页面后调用它,则隐式调用)