チャットメッセージをデータベースに保存していると思いますか?したがって、1つのアプローチは次のようになります。
最も重要なことは、最初に行う必要があるのはサーバー時間をユーザーに配信することです。これは新しいチャットメッセージを取得するための鍵であるため、最初にこれを行います。
var time;
$.ajax( {
url: 'http://yoursite.com/chat/get_time',
success: function( dataReponse ) {
time = dataResponse;
},
type: 'GET'
} );
URLに基づいて、という名前の関数で名前が"http://yoursite.com/chat/get_time"
付けられたコントローラーが必要です。この関数はサーバー時間をミリ秒単位で応答する必要があるため、次のようにします。"chat"
"get_time"
function get_time() {
echo time();
}
これで、サーバーへの新しいチャットメッセージのポーリングが開始され、次のようになります。
function getNewMsgs() {
$.ajax( {
url: 'http://yoursite.com/chat/get_new_msgs',
type: 'POST',
// send the time
data: { time: time },
success: function( dataResponse ) {
try {
dataResponse = JSON.parse( dataResponse );
// update the time
time = dataResponse.time;
// show the new messages
dataResponse.msgs.forEach( function( msg ) {
console.log( msg );
} );
// repeat
setTimeout( function() {
getNewMsgs();
}, 1000 );
} catch( e ) {
// may fail is the connection is lost/timeout for example, so dataResponse
// is not a valid json string, in this situation you can start this process again
}
}
} );
}
コントローラーにcomebacj 、関数"chat"
をコーディングする必要があり"get_new_msgs"
ます:
function get_new_msgs() {
$this->load->model( 'chat_msg' );
echo json_encode( array(
'msgs' => $this->chat_msg->start_polling(),
// response again the server time to update the "js time variable"
'time' => time()
) );
}
"chat_msg"
モデルでは、関数をコーディングします"start_polling"
。
function start_polling() {
// get the time
$time = $this->input->post( 'time' );
// some crappy validation
if( !is_numeric( $time ) ) {
return array();
}
$time = getdate( $time );
// -> 2010-10-01
$time = $time['year'] '-' + $time['mon'] + '-' + $time['mday'];
while( true ) {
$this->db->select( 'msg' );
$this->db->from( 'chat_msg' );
$this->db->where( 'time >=', $time );
$this->db->order_by( 'posted_time', 'desc' );
$query = $this->db->get();
if( $query->num_rows() > 0 ) {
$msgs = array();
foreach( $query->result() as $row ) {
$msgs[] = $row['msg'];
}
return $msgs;
}
sleep( 1 );
}
}
警告が表示されます。私はこのコードを頭の中で書きました。現時点では、このコードをテストするためのWebサーバーがありません。