PHP code inside a Javascript's “document.write()”

房东的猫 提交于 2020-01-10 05:03:38

问题


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


回答1:


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.




回答2:


The PHP gets evaluated before the JavaScript, so no need to escape the quotes.

document.write("<?php echo "Hello World"; ?>");



回答3:


when javascript runs that means the response is showing to the browser not compiling the php code any more so as you are putting php code in javascript that means you want something from server than no other alternate but ajax.




回答4:


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.




回答5:


If you need to execute some PHP code via javascript, you would need to have the PHP housed on a server somewhere where it can be run (i.e. the browser client will not run it) and then you need to used AJAX to run that script and do whatever you need to do with its output.



来源:https://stackoverflow.com/questions/11938805/php-code-inside-a-javascripts-document-write

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!