简体   繁体   English

如何从JavaScript访问PHP变量?

[英]How do I access a PHP variable from JavaScript?

如何在JavaScript中调用PHP变量或查询?

<script>
    var foo = <?php echo $foo; ?>;
    // or, if foo is a string;
    var foo = '<?php echo addslashes($foo); ?>';
    // for anything more complex, you'll need to use json_encode, if available in your version of PHP
    var foo = <?php echo json_encode($foo); ?>;
</script>

Please note, you can only do this one way. 请注意,您只能通过一种方式执行此操作。 Don't expect any changes you make in javascript to come through to PHP. 不要期望您在javascript中所做的任何更改都会传递到PHP。

PHP and JavaScript cannot mix directly. PHP和JavaScript不能直接混合使用。 You use PHP server-side to generate and send JavaScript to the client. 您使用PHP服务器端来生成JavaScript并将其发送到客户端。 the JavaScript executes client-side and can communicate with PHP code on the server only via AJAX calls. JavaScript执行客户端,并且只能通过AJAX调用与服务器上的PHP代码进行通信。 This can be simplified drastically through the use of an AJAX library like jQuery. 使用jQuery之类的AJAX库可以大大简化此操作。

You have to keep in mind that your PHP code is evaluated on the server, while JavaScript (normally) runs in the browser. 您必须记住,PHP代码是在服务器上评估的,而JavaScript(通常)是在浏览器中运行的。 The evaluations happen in different times, at different places. 评估发生在不同的时间,不同的地方。 Therefore you cannot call a JavaScript function (or variable) from PHP, simply because you cannot call a function that exists on another computer. 因此,仅由于无法调用另一台计算机上存在的函数,就无法从PHP调用JavaScript函数(或变量)。

You may want to check if Ajax is an appropriate solution for your problem. 您可能要检查Ajax是否适合您的问题。

Generally, you can't. 通常,您不能。 PHP is server-side and Javascript is client-side (processed by the browser). PHP是服务器端的,而Javascript是客户端的(由浏览器处理)。

The exception is to use AJAX, which allows you to access PHP pages, which should then execute the action needed. 例外是使用AJAX,它允许您访问PHP页面,然后应执行所需的操作。

You can use JSON for this purpose which serves well for sending a big array to Javascript from PHP. 您可以为此使用JSON ,它非常适合从PHP向Javascript发送大数组。 We need to echo JavaScript code in PHP script or we can use Ajax for this. 我们需要在PHP脚本中回显JavaScript代码,或者我们可以为此使用Ajax。 But usually we may need to send a big array. 但是通常我们可能需要发送一个大数组。 So we can do like this 所以我们可以这样

<script>
    <?php
        $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
    ?>
    var foo = echo json_encode($arr);
</script>

The json_encode function will handle all escaping and other issues. json_encode函数将处理所有转义和其他问题。 Bug also make sure json_encode is available in your PHP version. 错误还请确保json_encode在您的PHP版本中可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM