2017-09-25 79 views
0

我想用codeigniter创建聊天室,但有错误。如何通过ajax和codeigniter更新聊天室

这是我类Chat_model,我用AJAX调用updateChat()函数每秒。

我的问题是为什么变量$ old_rows总是返回相同的值$ new_rows

$ old_rows是变量获得数排在MySQL前添加消息)

class Chat_model extends CI_Model { 
    private $old_rows; 
    public function __construct() { 
      parent::__construct(); 
      //Do your magic here 
      $this->db->select('*');  
      $result = $this->db->get('chat'); 
      $this->old_rows = $result->num_rows(); 
    } 
    public function getRows() { 
      $this->db->select('*');  
      $result1 = $this->db->get('chat'); 
      return $result1->num_rows(); 
    } 
    public function addMessage($google_id,$message) { 
     //get number row before add message 
     $this->old_rows = $this->getRows(); 

     $date = date('Y-m-d H:i:s');   
     $data = array(
       'google_id'=>$google_id, 
       'message'=>$message, 
       'time_chat'=>$date  
     ); 

     $this->db->insert('chat', $data); 
     return $this->db->insert_id(); 
    } 
    public function updateChat() { 
     //get rows 
     $new_rows = $this->getRows(); 

     //get rows added 
     $new_rows_added = $new_rows - $this->old_rows; 

     //select rows added 
     $this->db->select('*'); 
     $this->db->order_by('time_chat', 'desc'); 
     $this->db->limit($new_rows_added); 

     $result = $this->db->get('chat'); 
     $result = $result->result_array(); 

     echo '$new_rows: '.$new_rows.' | '.'$this->old_rows: '.$this->old_rows; 
     die(); 
    } 
} 

回答

0

让您AJAX网址版本可以清除旧的结果缓存。

每次调用结果URL时都会附带一些新的v=1.12345随机标签。

http://www.example.com/chat?v=1.12345 

OR

$.ajax({ 
    type: "POST", 
    async: true, 
    url: "/chat/", 
    data: { 
     "action": action. 
     "model": model, 
     "object_id": object_id, 
     "position": position 
    }, 
    cache: false, 
    dataType: "json", 
    success: function(data){ 
     //[snip] 
    } 
}); 

缓存:假这里。