【发布时间】:2011-10-13 23:20:47
【问题描述】:
我可以通过使用<?php include("file.php") ?> 将 .php 文件加载到 div 中
该文件可以包含 php、javascript、html 和纯文本,但它仍然可以正常工作。
如果文件中有脚本标签,我无法将文件加载到我用 javascript 动态创建的 Div 中。
注意:我会随着我的进步更新代码
index.php
第一个 Div 效果很好,可以毫无问题地加载 test.php 文件。
<div id="phpDiv"
style="
position:absolute;
top: 50px;
left: 50px;
height: 200;
width: 300;
background-color: #CCCCCC;">
This is the phpDiv <br>
<?php include("test.php"); ?>
</div>
如果文件中有脚本标签,则动态创建的 Second Div 将不会加载文件
<script>
var javascriptDiv = document.createElement('div');
javascriptDiv.setAttribute('id', 'javascriptDiv');
javascriptDiv.style.position = 'absolute';
javascriptDiv.style.top = 350;
javascriptDiv.style.left = 50;
javascriptDiv.style.height = 200;
javascriptDiv.style.width = 300;
javascriptDiv.style.background = '#CCCCCC'; //so we can see that the DIV was created
<?php
//must have http:// in it to load php stuff
//will not load files with <script> tags
$file = file_get_contents('http://127.0.0.1/Debug/test.php');
//Trim the string and remove new lines.
$file = trim($file);
$file = str_replace("\n", "", $file);
$file = str_replace("\r", "", $file);
echo "javascriptDiv.innerHTML = \"This is the javascriptDiv <br>\"; ";
echo "javascriptDiv.innerHTML += '". $file ."';";
?>
document.body.appendChild(javascriptDiv); //Display the Window
</script>
test.php
<?php echo "php works <br>"; ?>
<script> alert('javascript works'); </script>
<a> html works </a><br><br>
and extra spaces and plain text work fine as well
【问题讨论】:
-
test.php 是什么样的?您是否在 PHP 中转义
'?文件中的所有内容都是一行,没有换行符,还是您为 JS 分块和连接该内容? -
如果浏览器看到这样的内容:jsfiddle.net/W3k7P 并且它不起作用,那是因为你不能像这样跨两行跨越变量。
-
您的 DIV 内容需要如下所示:jsfiddle.net/W3k7P/1 注意每一行的字符串连接,每行都被引用。
-
你渲染的源代码是什么样的? Javascript 控制台说什么?了解这些都非常有用:]
-
好吧,事情看起来好多了。现在我遇到的唯一问题是动态 Div 加载带有脚本标签的文件。它将加载其他所有内容。
标签: php javascript file dynamic innerhtml