简体   繁体   中英

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.

PHP and JavaScript cannot mix directly. You use PHP server-side to generate and send JavaScript to the client. the JavaScript executes client-side and can communicate with PHP code on the server only via AJAX calls. This can be simplified drastically through the use of an AJAX library like jQuery.

You have to keep in mind that your PHP code is evaluated on the server, while JavaScript (normally) runs in the browser. 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.

You may want to check if Ajax is an appropriate solution for your problem.

Generally, you can't. PHP is server-side and Javascript is client-side (processed by the browser).

The exception is to use AJAX, which allows you to access PHP pages, which should then execute the action needed.

You can use JSON for this purpose which serves well for sending a big array to Javascript from PHP. We need to echo JavaScript code in PHP script or we can use Ajax for this. 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. Bug also make sure json_encode is available in your PHP version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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