我已经为此挣扎了两个小时了,我已经将问题缩小到一个简单的测试用例。我做了大量的研究,最后决定尝试重现这个问题的第一个答案:用ajax设置会话变量。
当我按下这个按钮时(懒惰的html,但这不是问题所在):
<html>
<head>
...
<script src="jquery.js"></script>
...
<head>
<body>
....
<?php
var_dump($_SESSION);
?>
<input type="button" class="update">
....
</body>
</html>
这个ajax请求在jquery.js中被调用:
$.(".update").click(function() {
$.ajax({
type: "POST",
url:"setSession.php",
data: {bar: "foobar"},
success: function() {
console.log("Successful request sent");
}
});
最后是setSession.php文件:
<?php
session_start();
$_SESSION["foo"] = $_POST["bar"];
?>
成功消息被打印到控制台,所以我知道我正在击中正确的文件。为什么没有设置会话变量?我有php 5.5.2,如果这很重要。谢谢你的帮助!
就像我在注释中建议的那样,这样做来修复你的代码:
在success
上重新加载页面:
success: function() {
console.log("Successful request sent");
location.reload();
}
确保在所有使用会话的页面中都有session_start()
:
session_start(); //this must be at the top, before you print anything
可能对你有帮助。
在setSession.php
中写echo $_SESSION["foo"] = $_POST["bar"];
在ajax脚本中执行
$.(".update").click(function() {
$.ajax({
type: "POST",
url:"setSession.php",
data: {bar: "foobar"},
success: function(e) {
console.log(e);
}
});
现在打开浏览器console
(F12
)。点击按钮,更新。检查控制台是否有写bar