Php 为什么使用AJAX返回的Javascript代码不';t使用指定的格式写入<;部门>;,但它取代了整个页面?
我使用AJAX(使用jQuery)请求一个标记,该标记包含对Apache+PHP服务器的Javascript函数调用。以下是HTML和AJAX代码:Php 为什么使用AJAX返回的Javascript代码不';t使用指定的格式写入<;部门>;,但它取代了整个页面?,php,javascript,jquery,ajax,Php,Javascript,Jquery,Ajax,我使用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> <scri
<!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>
AJAX请求页面的http://localhost/test.php'其中包含以下PHP代码:
<?php
echo '<script type="text/javascript"> document.write("Javascript output"); </script>';
?>
当我点击链接时,在AJAX请求之后,整个页面被替换为“Javascript输出”,而不是只在id为“container”的div标记中写入
如果PHP服务器脚本编写了其他内容,而不是这样的脚本标记:
<?php echo 'text' ?>
AJAX调用的行为正常,将div替换为id“container”,而不是整个页面
我尝试使用Wireshark调查此页面传输的HTTP数据,但这似乎不是HTTP问题,因为服务器响应正是应该的:
<script type="text/javascript"> document.write("Javascript output"); </script>
document.write(“Javascript输出”);
不使用AJAX运行Javascript代码不会替换整个页面,只有在使用AJAX返回脚本标记时才会发生这种情况。A注意到Firefox 3和5以及Google Chrome中的相同行为
为什么会发生这种情况?
文档。write
通常在页面的主加载期间使用,在此期间,它输出到浏览器读取以呈现主页的解析流。如果您在页面初始加载完成后使用它,它会隐式地对文档执行打开
,这会完全撕毁文档,并以新编写的内容重新开始
简短版本为:仅使用文档。在主页加载期间写入(如果有)。加载页面后,改用DOM操作
示例():
有关、和的更多信息:
document.write
:|
document.open
:| |
(由document.write隐式调用,如果在加载页面后调用它)
因为jQuery将识别javascript块并针对页面而不是目标容器运行它。
document.write(“Javascript输出”);
既然您正在更改$(“#container”)的值,那么为什么不直接返回“JavaScript输出”呢?无论如何,没有必要尝试使用内联JavaScript文档。write来写出来。为什么要返回此文档。从服务器端写东西?正如您可以在Ajax的成功块中执行此操作一样,此代码只是一个示例。我需要从服务器端返回document.write,因为Javascript实际要写的内容取决于某些服务器端变量。@Calin:如果内容因服务器端变量而异,则可以使用服务器端处理来输出适当的内容。Ya,准确地说------只需返回这些计算出的变量,并在成功块------文档中使用它们。编写(processedVar)谢谢!我不知道那个文档。页面加载后不得使用write。这对我来说似乎很重要。@Calin:的确如此。在页面加载期间使用它的用例是…有限的。:-)
<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>
<script type="text/javascript"> document.write("Javascript output"); </script>