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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号