为什么我不能从我的AJAX调用的PHP脚本中访问会话变量?
我有一个带有会话变量的PHP脚本,设置如下:
$_SESSION['VAR1'] = "test"
现在,我通过jQuery启动的POST请求使用AJAX,因此我有一个名为ajax.php
的脚本,它具有所有必需的function。
当我尝试在ajax.php中访问我的会话变量( echo $_SESSION['VAR1']
)时,它什么都不产生。
会话在AJAX请求中不起作用吗?
您需要在访问会话之前访问会话的每个页面上执行此操作:
session_start();
这意味着在设置会话变量的页面和尝试检索它的AJAX页面上。 两者都需要调用session_start()
。
只要AJAX请求调用同一域中的脚本(从而获得对会话cookie的访问权限),就没有理由无法访问会话变量。 毕竟,AJAX请求只是另一个HTTP请求。
确保两个页面的域名(即AJAX容器和AJAX脚本相同)。 这是一个例子:
http://mydomain.com/login.php (set session variables here) http://mydomain.com/ajax-container.php (session variables are visible here) http://mydomain.com/ajax-script.php (session variables are visible here) http://www.mydomain.com/ajax-script.php (session variables are NOT visible here)
另一个:
http://www.mydomain.com/login.php (set session variables here) http://www.mydomain.com/ajax-container.php (session variables are visible here) http://www.mydomain.com/ajax-script.php (session variables are visible here) http://mydomain.com/ajax-script.php (session variables are NOT visible here)
我还发现自己在“<?php”之前有一个小的,很小的,很难看到的空间。这最终发回信息并禁止会话开始,因为标题信息已经发送。 可能不是其他任何人的情况,但它绊倒了我并带我到这个页面寻找答案。
在调用session_start()之前,确保没有回显任何内容(甚至不是空格)。
为了安全起见,将代码作为您用于页面的任何模板的第一个代码。 如果已将内容发送到浏览器,则该function将不起作用。
要测试并查看问题所在,请将该页面作为独立页面调用,而不是通过AJAX调用,并确保它在AJAX之前可以正常工作。
Salman A所写的附录:
如果您在https://文件中设置会话变量并尝试使用http://文件访问它,您将无法…
https://www.example.com/index.php - call session_start() and set session variable http://ww.example.com/index_tmp.php - unable to access session variable
反之亦然……
http://www.example.com/index.php - call session_start() and set session variable https://ww.example.com/index_tmp.php - unable to access session variable
而是:
https://www.example.com/index.php - call session_start() and set session variable https://ww.example.com/index_tmp.php - Able to access session variable
和:
http://www.example.com/index.php - call session_start() and set session variable http://ww.example.com/index_tmp.php - Able to access session variable
我自己的错误是我的ajax文件中的BOM字符。我需要在一个名为php file的ajax中使用会话变量。我试图通过session_start()启动会话但是“无法修改标题信息”发生。我删除了BOM字符和代码工作很好。
在jQuery或JavaScript中,您可以获得如下的会话值:
var StepIndexval = '<%= Session["StepIndex"].ToString() %>'; alert(StepIndexval);