如何在JavaScript或jQuery中访问PHP变量而不是<?php echo $ variable?>
如何在JavaScript或jQuery中访问PHP变量?我是否必须写
How do I access PHP variables in JavaScript or jQuery? Do I have to write
<?php echo $variable1 ?>
<?php echo $variable2 ?>
<?php echo $variable3 ?>
...
<?php echo $variablen ?>
我知道我可以在cookie中存储一些变量,并通过cookie访问这些值,但cookie中的值是相对稳定的价值观。而且,有一个限制,你不能在cookie中存储很多值,并且方法不那么方便。有没有更好的方法呢?
I know I can store some variables in cookies, and access these values via cookies, but values in cookies are relatively stable values. Moreover, there is a limit, you can not store many values in cookies, and the method is not that convenient. Is there a better way to do it?
您的示例显示了将PHP变量传递给JavaScript的最简单方法。您还可以使用json_encode来处理更复杂的数据:
Your example shows the most simple way of passing PHP variables to JavaScript. You can also use json_encode for more complex things like arrays:
<?php
$simple = 'simple string';
$complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
var simple = '<?php echo $simple; ?>';
var complex = <?php echo json_encode($complex); ?>;
</script>
除此之外,如果你真的想在PHP和JavaScript之间互动,你应该使用Ajax。
Other than that, if you really want to "interact" between PHP and JavaScript you should use Ajax.
使用cookie是一种非常不安全和不可靠的方式,因为它们存储在客户端,因此可以进行任何操作,甚至不会被接受/保存。不要将它们用于此类交互。
jQuery.ajax 是一个很好的开始恕我直言。
Using cookies for this is a very unsafe and unreliable way, as they are stored clientside and therefore open for any manipulation or won't even get accepted/saved. Don't use them for this type of interaction. jQuery.ajax is a good start IMHO.