【问题标题】:codeigniter ajax request with session带有会话的codeigniter ajax请求
【发布时间】:2016-09-12 06:27:54
【问题描述】:

无法通过 ajax 请求获取会话值

这是我的ajax请求

$.post(url, payload, 
    function(returnedData){
        console.log(returnedData); //does not print session values it seems session has restarted
         var jsonData = JSON.parse(returnedData);

         $('#cart').empty().append(jsonData.data);
});

console.log 中的输出

    Array
(
    [__ci_last_regenerate] => 1473660791
)

分配会话变量

public function test($id=null)
{
    $_SESSION['tot']=1;
}

不使用 ajax 进行测试

public function addToCart($id=null) //note that this is also the control for my ajax req
{            
        print_r($_SESSION);
        die('0');
}
public function test1()
{
    print_r($_SESSION); // it prints fine
}

输出

Array ( [__ci_last_regenerate] => 1473660731 [tot] => 1 )

我自动加载我的会话库。 CI 表示,只要存在会话变量,使用会话魔术或 php 访问会话变量的方式并不重要。

【问题讨论】:

  • 如果你使用 php session 那么你需要在访问 $_SESSION 变量之前隐式启动 session_start()。
  • 我正在使用 codeigniter 会话并自动加载它。
  • 如果你使用代码点火器会话然后访问它 $session_id = $this->session->userdata('session_id');
  • 相信也和通过$_SESSION['name']访问是一样的。这个我已经试过了,还是不行。

标签: php jquery ajax codeigniter session


【解决方案1】:

您好,您可以使用默认的 codeignitor 会话,请说明您发出 ajax 请求的 url 和 ajax 请求的 php 代码

喜欢

$this->session->set_userdata('tot',1);

然后像这样打印会话数组

echo "<pre">;print_r($this->session->userdata('tot'));

【讨论】:

  • 好吧,我试试那个
  • 还是一样。当我没有通过 ajax req 访问它时,它打印正常。
  • 所以只有 addToCart 功能它不会打印,其他功能它会打印好吗?
  • 如果不是通过 ajax 请求,"addToCart" 也会打印 ok。假设如果我只是在我的 url 栏中直接访问“addToCart”,就像输入整个域(例如localhost/khloe/welcome/addtocart),它打印得很好。但是如果我使用像“$.post()”这样的ajax请求,那么它就不起作用。我希望你明白我想说的话。顺便感谢您的快速回复
【解决方案2】:

你的代码应该是

 public function test($id=null)
    {
        $this->session->set_userdata('tot', 1);
        //instead $_SESSION['tot']=1;
    }
    public function addToCart($id=null) //note that this is also the control for my ajax req
    {            
            $session_id = $this->session->userdata('session_id');
echo $session_id;
    }
    public function test1()
    {
        //print_r($_SESSION); // it prints fine
$session_id = $this->session->userdata('session_id');
echo $session_id;
    }

并确保已加载会话库 ($this->load->library('session');)

【讨论】:

    猜你喜欢
    • 2017-02-23
    • 2018-08-12
    • 2016-05-05
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多