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);
    }
    });
    
    点赞 评论

相关推荐 更多相似问题