在 JavaScript 中插入 PHP 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13099497/
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
Inserting PHP code inside JavaScript
提问by Srivathsan
Possible Duplicate:
php in javascript?
可能的重复:
javascript 中的 php?
I need to check an if condition inside the inner html property of javascript. And so for that I need to use php inside it. So is it possible. I tried the following and it doesn't seem to work.
我需要检查 javascript 内部 html 属性中的 if 条件。因此,我需要在其中使用 php。那么有可能吗。我尝试了以下方法,但似乎不起作用。
document.getElementById().innerHTML =
"<?php if ($number == 1) { echo $ex; } else { echo $ey; } ?>";
So please help me out with this problem.
所以请帮我解决这个问题。
回答by Anirudh Ramanathan
Your PHP is executed at the server. Once the page has been fetched, inserting PHP code into it at the client end via JavaScript, will notcause it to be executed.
您的 PHP在服务器上执行。一旦页面被抓取,在客户端通过 JavaScript 将 PHP 代码插入其中,不会导致它被执行。
You should store $number
, $ex
, $ey
in JavaScript variables and perform the same comparison in JavaScript.
您应该将$number
, $ex
,存储$ey
在 JavaScript 变量中并在 JavaScript 中执行相同的比较。
Firstly,
第一,
<script type="text/javascript">
var number = <? echo $number ?>
var ex = <? echo $ex ?>
var ey = <? echo $ey ?>
</script>
The above sets the values of JS variables. Afterwards, you can call:
以上设置了JS变量的值。之后,您可以调用:
if (number == 1) { document.getElementById().innerHTML = ex; }
回答by Saurabh
Try this
试试这个
<?php
if ($number == 1){ ?>
document.getElementById().innerHTML = $ex;
<?php }
else
{ ?>
document.getElementById().innerHTML = $ey;
<?php } ?>