0

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

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中,我尝试echo这样做session。这是函数示例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);
    }
});

问题是,我不能实时显示存储在会话中的数据,我必须刷新页面才能得到结果。有什么线索吗?

4

1 回答 1

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);
}
});
于 2013-05-12T10:13:02.537 回答