![](/img/trans.png)
[英]Javascript change inner html of div that contains php include
[英]Unable to load PHP file into a inner HTML Div created dynamically with javascript
我可以简单地使用<?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
我会说这是行不通的,因为您在设置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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.