开发者

How do I access a PHP variable from JavaScript?

How do I call PHP variables or queries in JavaScript开发者_Python百科?


<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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜