简体   繁体   中英

[PHP/JavaScript]: Get PHP session value in other file's JavaScript function

I have a PHP file and it holds a value in this session variable: $_SESSION['image_value'].

I want this session value in a JavaScript function. Actually, I want to match a string in my JavaScript function with this session value.

Anyway I can do this?

You could use json_encode():

<script type="text/javascript">
    var image_value = <?php echo json_encode($_SESSION['image_value'], JSON_HEX_TAG); ?>;
</script>

But be aware that PHP is entirely server-side and javascript is entirely client-side. That variable will be set when the page loads and any javascript modifications to it will not be preserved in the session.

In your javascript code, instantiate x like this:

var x = "<?=$_SESSION['image_value']?>";

then just use it to do your comparisons or whatever. Of course, the script has to be evaluated by the server first, so putting this inside a .js file will not work. You need to put this in the .php file, in a tag. Maybe to this then call a function in a js file if you need to.

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