在 PHP 中使用 JS 变量 [英] using JS variable in PHP

查看:50
本文介绍了在 PHP 中使用 JS 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 PHP 中像这样使用 JS 变量?

how can use JS variable in PHP like this ?

<script>
x = document.getElementById(1).value;
var listOf = <?php echo $listOf[x]; ?>;
</script>

这不起作用:(

推荐答案

理所当然.PHP 在服务器上执行,而 JavaScript 在客户端的浏览器中执行.这是两个不同的上下文,其中一个的变量在第二个中不可见.

And rightfully so. PHP is executed on the server, while JavaScript is executed in the client's browser. Those are two different contexts and the variables from one are not visible in the second.

您需要让您的 PHP 脚本输出数组的 JavaScript 版本,然后在您的脚本中使用这个版本.像这样:

You need to have your PHP script output a JavaScript version of the array and then use this one in your script. Something like this:

<?php
echo "listArray = new Array();\n";
foreach ($listArray as $key => $value) {
   echo 'listArray[', $key, '] = ', $value, ";\n";
}

这篇关于在 PHP 中使用 JS 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆