如何将 PHP 变量与 JavaScript 变量连接起来?是否可以?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17850550/
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 to concatenate PHP variable with JavaScript Variable? Is it possible?
提问by sami
Java Script Code:
Java脚本代码:
<script type="text/javascript">
$(function () {
var seatNo = 2;
str.push('<a title="' + seatNo + '">' + '<?php echo $thisPacket["seat"]; ?>'</a>');
});
</script>
I want to concatenate between $thisPacket["seat"]with java Script variable seatNo.
Just like php concate. example: $i = 1; $thisPacket["seat".$i];
我想在$thisPacket["seat"]与 java Script 变量之间进行连接,seatNo.
就像 php concate 一样。例如:$i = 1; $thisPacket["seat".$i];
回答by Hein Andre Gr?nnestad
I want to concatenate between $thisPacket["seat"] with java Script variable seatNo. Just like php concate. example: $i = 1; $thisPacket["seat".$i];
我想在 $thisPacket["seat"] 与 java 脚本变量seatNo 之间连接。就像 php concate 一样。例如:$i = 1; $thisPacket["seat".$i];
No, this won't work because the PHP code runs on the server, and the javascript variable seatNois not available until the javascript code executes on the client.
不,这是行不通的,因为 PHP 代码在服务器上运行,并且seatNo在 javascript 代码在客户端上执行之前,javascript变量不可用。
回答by Mohammad Ismail Khan
take you php variable and assign it to javascript variable than concatenate them.
带你 php 变量并将其分配给 javascript 变量而不是连接它们。
var phpVar = '<?php echo $thisPacket["seat"]; ?>';
var seatNo = 2;
var conVar = seatNo + phpVar;
I hope this will work
我希望这会奏效
回答by EJTH
Your best bet is to serialize $thisPacketas a JSON object and send that to the client:
最好的办法是将其序列$thisPacket化为 JSON 对象并将其发送给客户端:
<script type="text/javascript">
var thePacket = <?=json_encode($thisPacket);?>;
$(function () {
var seatNo = 2;
str.push('<a title="' + seatNo + '">' + thePacket['seat'+seatNo] + '</a>');
});
</script>
But im guessing that you should really reconsider your current design.
但我猜你真的应该重新考虑你当前的设计。
回答by frogatto
No this is impossible, because JavaScript is a client-side language and will be executed after that all PHP commands was executed in the server and the page completely rendered. But PHP is a server-side language and is execued before any JavaScript code is interpreted.
不,这是不可能的,因为 JavaScript 是一种客户端语言,将在服务器中执行所有 PHP 命令并完全呈现页面之后执行。但 PHP 是一种服务器端语言,在解释任何 JavaScript 代码之前执行。
回答by freshp
this should work
这应该有效
<script type="text/javascript">
$(function () {
var seatNo = 2;
str.push('<a title="' + seatNo + '"><?php echo $thisPacket["seat"]; ?></a>');
});
</script>

