简体   繁体   中英

How to access a session variable in a .js file in CakePHP

In my CakePHP application I am creating a session variable in some controller, which I need to access in a ".js" file. Is there any possible way to do this?

I would suggest passing them as parameters like this -

<a onclick="some_function('<?php echo $_SESSION['var'] ?>')">Click</a>

and have the javascript function some_function() process it instead of assigning them inline. This way you can have the javascript file free from server side code. This is the cleanest way.

I too feel that because session variables are server side, they should not be handled directly in client side language through inline code.

You need to dynamically generate your JS file so that it contains the value you want. You can set up your server to parse .js files through PHP, or you can just name the JS file .php :

var myVar = '<?php echo addslashes($_SESSION['myVar']); ?>';

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