我正在创建一个聊天框,检索会话中保存的user_id,然后使用ajax帖子,但由于某种原因,保存在会话中的user_id为空,而不是保存在数据库中,我现在已经存货了。 / p>
控制器
function add_chat_messages() {
// Grab the $chat_message_content, $user_id and $chat_id
$user_id = $this->session->userdata("user_id");
$chat_message_content = $this->input->post('chat_message_content');
$this->abt_db->add_chat_message($user_id, $chat_message_content);
}
模型
function add_chat_message($user_id, $chat_message_content) {
$query_str = "INSERT INTO chat_message(user_id, chat_message_content) VALUES (?,?)";
$this->db->query($query_str, array($user_id, $chat_message_content));
}
function set_session() {
// session->set_userdata is a CodeIgniter function that
// stores data in a cookie in the user's browser. Some of the values are built in
// to CodeIgniter, others are added (like the user_id).
$this->session->set_userdata(array(
'user_id' => $this->details->user_id,
'email' => $this->details->email,
'username' => $this->details->username,
'isLoggedIn' => true
)
);
}
查看
<script type="text/javascript">
var user_id = "<?php echo $this->session->userdata('user_id'); ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
<!--loads the header-->
<?php $this->load->view('abt-header'); ?>
<!--this is the login page-->
<div data-role="page" id="Abt-chat" data-add-back-btn="true">
<div data-role="header" data-position="fixed">
<h1>Peer Chat</h1>
</div>
<div data-role="content">
<div data-role="fieldcontain">
<div id="chat_viewport"></div>
<p>
<label>Input Chat: </label>
<input name="chat" id="chat" type="text" value=""/>
</p>
<p>
<?php echo anchor('#', 'Send Chat', array('title' => 'Send Chat', 'id' => 'submit')); ?>
</p>
</div>
<?php echo form_close(); ?>
</div>
</div>
Javascript文件
$(document).bind("mobileinit", function(){
$.mobile.ajaxEnabled = false;
});
$(document).ready(function(){
$("a#submit").click(function(){
var chat_message_content = $("input#chat").val();
if(chat_message_content == ""){
return false;
}
$.post(base_url + "index.php/abovetheblues/add_chat_messages", {
chat_message_content : chat_message_content,
user_id : user_id
},
function(data){
alert(data);
},"json");
return false;
});
return false;
});