Javascript 的“document.write()”中的 PHP 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11938805/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:45:57  来源:igfitidea点击:

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

phpjavascripthtmldomdocument.write

提问by wanovak

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.

我需要在 Javascript 的“ document.write()”中编写一些 PHP 代码。这是一个虚拟示例,但将来 Javascript 将自动生成该 PHP 代码。

This is the Hello World I have coded:

这是我编写的 Hello World:

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:

但是,没有显示任何内容,在 DOM 文件中我得到了这个:

<html>
<body>
<script type="text/javascript">
<!--?php echo  "Hello World"; ?-->
</script>
</body>
</html>

Any help? Thanks

有什么帮助吗?谢谢

采纳答案by Guerra

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.

不可能。Php 需要在服务器端运行,而 javascript 只在客户端运行。您可以做的是准备一个 php 代码来编写一个文件并通过 javascript 调用此代码。

回答by wanovak

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

PHP 在 JavaScript 之前被评估,所以不需要转义引号。

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

回答by ARIF MAHMUD RANA

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.

当 javascript 运行时,这意味着响应显示给浏览器不再编译 php 代码,因此当您将 php 代码放入 javascript 时,这意味着您希望从服务器获得一些东西,而不是其他替代品,而是 ajax。

回答by colonelclick

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.

你问的是不可能的。服务器完成后,Javascript 生成 php 代码客户端。服务器永远不会看到 PHP 代码。

回答by Mike Brant

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.

如果您需要通过 javascript 执行一些 PHP 代码,您需要将 PHP 放在可以运行的服务器上(即浏览器客户端不会运行它),然后您需要使用 AJAX 来运行该脚本和对它的输出做任何你需要做的事情。