2017-09-25 75 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] 
    } 
}); 

緩存:假這裏。