如何使用 PHP 更改innerHTML?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15867105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I change innerHTML with PHP?
提问by user2255325
I want to change the innerHTML with PHP code. But I cannot get it to work, and I do not understand why. I want it to change some text on the page but from another file. And so I thought that I could use this:
我想用 PHP 代码更改innerHTML。但我无法让它工作,我不明白为什么。我希望它更改页面上的一些文本,但来自另一个文件。所以我想我可以使用这个:
document.getElementById ("page"). innerHTML = "<? php echo $ home?>";
But it does not work.
但它不起作用。
Here is my code:
这是我的代码:
<?php
$home = file_get_contents("home.php");
?>
<script type="text/javascript">
function ChangePage(page)
{
if(page == "home")
{
document.getElementById("page").innerHTML = "<?php echo $home ?";
}
}
</script>
回答by Francisco Presencia
There are many small typos. Try removing the space between $ and 'home' and before 'php'. This is the right statement:
有很多小错别字。尝试删除 $ 和 'home' 之间和 'php' 之前的空格。这是正确的说法:
document.getElementById ("page"). innerHTML = "<?php echo $home?>";
Also, where's your closing php tag?
另外,你的 php 结束标签在哪里?
<?php
$home = file_get_contents("home.php");
?>
<script type="text/javascript">
function ChangePage(page)
{
if(page == "home")
{
document.getElementById("page").innerHTML = "<?php echo $home; ?>";
}
}
</script>
Although this is a bad practice. Why would you want to do this instead of simply loading the php in the right place? Also, you do realize that 'page' should be the id of a pre-existing div in your html, right? Something like this would be better:
虽然这是一个不好的做法。为什么要这样做而不是简单地将 php 加载到正确的位置?此外,您确实意识到“页面”应该是 html 中预先存在的 div 的 id,对吗?这样的事情会更好:
<html>
<body>
<div id = "page">
<?php echo file_get_contents("home.php"); ?>
</div>
</body>
</html>

