如何在 JavaScript 或 jQuery 中访问 PHP 变量,而不是 <?php echo $variable ?>

2022-01-30 00:00:00 jquery php javascript

如何在 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 中的值是相对稳定的值.而且,有一个限制,cookies中不能存储很多值,方法也不是很方便.有没有更好的方法?

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.

相关文章