我可以简单地通过使用<?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>
动态创建的第二个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
我会说它不起作用,因为你在你的单引号语句中使用了单引号来设置你的innerHTML。
<?php echo "php works <br>"; ?>
<script> alert("javascript works"); </script>
<a> html works </a><br><br>
编辑:你可以尝试像这样自动去掉换行符:
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en'r'n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('test.php', false, $context);
$file = str_replace( "'r'n", "", $file );
将$file放入innerHTML
试着看看这段代码。我成功了。创建index.php代码,并将Jquery文件放在该目录中。从这里下载http://jquery.com/download/.
<html lang="en">
<head>
<meta charset="utf-8">
<title>load demo</title>
<style>
body{ font-size: 12px; font-family: Arial; }
</style>
<script src="jquery.js"></script>
</head>
<body>
<b>Successful Response (should be blank):</b>
<div id="success"></div>
<b>Error Response:</b>
<div id="error"></div>
<script>
var browser=navigator.userAgent;
//if (browser.lastIndexOf("Chrome")>=5)
{
alert("ok");
$("#success").load("index.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
}
});
}
</script>
</body>
</html>