dtlhy0771 2013-05-11 19:17
浏览 40
已采纳

Codeigniter:将数据保存到会话并使用Ajax显示它

I ran into issue with sessions and ajax. I have this peace of code:

for ($i=0; $i < count($result); $i++) {
    if(in_array($result[$i], $m_lines_arr)) {
        echo "<p class='br' style='color:   #ffffff'>Match on comb. $i</p>";
        $win = 10;
        $this->session->set_userdata( array('win' => $win));
    }
    else {
        echo "<p class='br'>No match on comb. $i</p>";
    }
}

So, if something is in array, give $win value 10 and save it do session, otherwise just do simple echo. In my function win I try to echo this session. Here is the sample of function win:

function win() {
    $win = $this->input->post('win');
    echo $this->session->userdata('win');
}

Function win comes after the for loop, just for you to know.

And here is the Ajax request:

var win = $('#win span').html();
$.ajax({
    type: 'POST',
    url: 'http://localhost/slots/index.php/game/win',
    data: { win: win },
    success:function(response) {
        $('#win span').html(response);
    }
});

The problem is, I can't display data stored in session in real time, I must refresh page to get the result. Any clue?

  • 写回答

1条回答 默认 最新

  • dongyu4908 2013-05-12 10:13
    关注
    function win() {
        echo $win = $this->input->post('win');
        // $this->session->userdata('win'); i don't think you need this if it's real time
    }
    

    but i prefer usually:

    function win() {
        $win = $this->input->post('win');
        echo json_encode( array('win'=>$win));
    }
    

    then in ajax:

    $.ajax({
     //...
    dataType:'json',
     success:function(json){
     alert(json.win);
    }
    });
    

    NB, VERY VERY IMPORTANT, the session must be setted BEFORE any output, so here you are setting session after the output:

     echo "<p class='br' style='color:   #ffffff'>Match on comb. $i</p>";
            $win = 10;
            $this->session->set_userdata( array('win' => $win));
    

    do this:

    $win = 10;
     $this->session->set_userdata( array('win' => $win)); //for better performance you must call this out from the loop
    echo ."<p class='br' style='color:   #ffffff'>Match on comb. $i</p>";
    
    
        then in ajax:
    
    $.ajax({
     //
    success:function(response){
     alert(response);
    }
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊