2013-05-11 73 views
0

我遇到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

回答

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({ 
//... 
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

相關問題