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

问题描述:

我遇到sessionsajax问题。我有这样的和平代码:Codeigniter:将数据保存到会话并使用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); 
    } 
}); 

的问题是,我不能显示存储在会话中的实时数据,我必须刷新页面以获取结果。任何线索?

+0

什么时候循环得到执行? ajax调用脚本吗? – SachinGutte 2013-05-11 19:26:35

+0

每次按下一个按钮,但该循环无关紧要。我有数据存储在会话中,但ajax刷新后检索它。 Ajax在document.ready函数 – mihajloWR 2013-05-11 19:29:37

+0

'$ result'里面有什么? – 2013-05-11 19:40:54

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({ 
//... 
dataType:'json', 
success:function(json){ 
alert(json.win); 
} 
}); 

NB,非常非常重要的是,必须对会话设置好的之前的任何输出,所以在这里你设置会话后输出:

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); 
} 
}); 
+0

现在就试试看。 – mihajloWR 2013-05-12 10:18:19

+0

@mihajloWR当然,让我现在;) – sbaaaang 2013-05-12 10:19:25

+0

好吧,所以我需要以相反的顺序?我忘了提及,在我的if(in_array ...)我必须实时输出到我的html代码

\t \t \t \t Win : 0 \t \t \t
mihajloWR 2013-05-12 10:29:37