I need to write some PHP code inside a Javascript's " document.write()
". This is a dummy example, but in the future Javascript will generate automatically that PHP code.
This is the Hello World I have coded:
MyFile.php
<html>
<body>
<script type="text/javascript">
document.write("<?php echo \"Hello World\"; ?>");
</script>
</body>
</html>
However, nothing is displayed, and in the DOM file I get this:
<html>
<body>
<script type="text/javascript">
<!--?php echo "Hello World"; ?-->
</script>
</body>
</html>
Any help? Thanks
PHP在JavaScript之前先经过评估,因此无需转义引号。
document.write("<?php echo "Hello World"; ?>");
当javascript运行时,这意味着响应正在显示给浏览器,而不再编译php代码,因此将php代码放入javascript中意味着您希望从服务器获得某种东西,而除了ajax之外,别无其他选择。
What you ask is not possible. Javascript generates the php code client side, after the server is finished. The server never sees the PHP code.
It's impossible. Php need server-side to runs, and javascript runs just on client side. What you can do is prepare one php code to write one file and call this code by javascript.
如果您需要通过javascript执行一些PHP代码,则需要将PHP放在可以运行它的服务器上(即浏览器客户端不会运行它),然后您需要使用AJAX来运行该脚本并用它的输出做任何您需要做的。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.