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?
答
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);
}
});