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

时间:2013-05-11 19:17:36

标签: php jquery ajax codeigniter

我遇到了sessionsajax的问题。我有这样的代码和平:

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>";
    }
}

因此,如果某些内容在数组中,请提供$win10并将其保存为会话,否则只需执行简单的回显。 在我的函数win中,我尝试echosession。以下是函数win的示例:

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

Function win位于for loop之后,仅供您了解。

这是Ajax请求:

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);
    }
});
问题是,我无法实时显示会话中存储的数据,我必须刷新页面才能得到结果。任何线索?

1 个答案:

答案 0 :(得分:1)

function win() {
    echo $win = $this->input->post('win');
    // $this->session->userdata('win'); i don't think you need this if it's real time
}

但我通常更喜欢:

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

然后在ajax:

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

注意,非常非常重要,必须在任何输出之前设置会话,因此您在输出后设置会话:

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

这样做:

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