[英]How to include PHP $_SESSION values in a javascript file?
I use $_SESSION['siteRoot']
to store the root address of my website in (it's basically a framework so this can change depending on the URL used to access the site). 我使用
$_SESSION['siteRoot']
将网站的根地址存储在(基本上是一个框架,因此可以根据用于访问该站点的URL进行更改)。 I need to use this value in some of my javascript files... 我需要在某些javascript文件中使用此值...
Up until now I've been including my js files as .php
, and putting the following code at the top of my js
files, like so: 到目前为止,我一直将js文件包含为
.php
,并将以下代码放在js
文件的顶部,如下所示:
<?php
header("Content-type: application/javascript");
session_start();
?>
This has been working fine on my local-host for testing - but when I upload it to the live server I noticed that my session was being reset every time I reload the page, and after a day of debugging finally discover that it's the session_start(); 在我的本地主机上进行测试时,这已经可以正常工作了,但是当我将其上传到实时服务器时,我注意到每次重新加载页面时,会话都被重置了,经过一天的调试,最终发现它是session_start( ); line in my java-script files that is causing this behavior.
我的Java脚本文件中的一行导致了此行为。
I've tried the following: 我尝试了以下方法:
if (!isset($_SESSION))
{
session_start();
}
if (session_id() == '')
{
session_start();
}
if (session_status() !== PHP_SESSION_ACTIVE)
{
session_start();
}
and also just leaving out the session_start altogether. 并且也完全省略了session_start。 If I don't start the session then I can't use the variables (obviously...), but I can't find a way of starting it that doesn't wipe the session I already created in my main page.
如果我不启动会话,那么我将无法使用变量(显然是...),但是我找不到启动该方法的方法,因此无法擦除我已经在主页上创建的会话。
Any ideas? 有任何想法吗?
The problem was not caused by the session itself exactly, but because I hadn't included my class autoloader before calling the session, and so my custom classes were not surviving the deserialize process (even though it's a javascript file and I don't use any of said classes!) 问题不是完全由会话本身引起的,而是因为在调用会话之前我没有包括我的类自动加载器,所以我的自定义类无法在反序列化过程中幸存下来(即使它是一个javascript文件,我也不使用)任何上述课程!)
I changed my javascript code to: 我将JavaScript代码更改为:
<?php
include ('include/autoloader.php');
header("Content-type: application/javascript");
session_start();
?>
and everything works fine. 一切正常。 Easy to forget when you're not using any of the serialized classes on that page!
当您不使用该页面上的任何序列化类时,很容易忘记!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.