ajax的新手,无法使用post请求设置会话变量

时间:2016-08-23 05:13:10

标签: php jquery ajax session

我现在已经挣扎了两个小时了,我已经把这个问题缩小到一个简单的测试用例。我做了大量的研究,最后决定尝试重现这个问题的第一个答案:Set session var with ajax

当我按下这个按钮时(懒惰的HTML,但那不是问题所在):

<html>
<head>
...
<script src="jquery.js"></script>
...
<head>
<body>
....
<?php
    var_dump($_SESSION);
?>
<input type="button" class="update">
....
</body>
</html>

jquery.js中的这个ajax请求被调用:

$.(".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,如果这很重要的话。谢谢你的帮助!

2 个答案:

答案 0 :(得分:0)

就像我在评论中建议的那样,这样做是为了修复你的代码:

success上重新加载页面:

success: function() {
            console.log("Successful request sent");  
            location.reload();
        }  

确保在使用会话的所有页面中都有session_start()

session_start(); //this must be at the top, before you print anything

答案 1 :(得分:-1)

这可以帮助你。

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);

        }
});

现在打开浏览器consoleF12)。点击你的button.update。检查控制台中是否写有bar

相关问题