简体   繁体   English

如何在CakePHP中访问.js文件中的会话变量

[英]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. 在我的CakePHP应用程序中,我正在某个控制器中创建一个会话变量,我需要在“ .js”文件中进行访问。 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. 并让javascript函数some_function()处理该事件,而不是内联分配它们。 This way you can have the javascript file free from server side code. 这样,您就可以从服务器端代码中释放javascript文件。 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. 您需要动态生成JS文件,使其包含所需的值。 You can set up your server to parse .js files through PHP, or you can just name the JS file .php : 您可以将服务器设置为通过PHP解析.js文件,也可以仅将JS文件命名为.php

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

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

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