对于投票的人来说,这不是一个真正的问题,绝对是愚蠢的。
我已经用Google搜索了一个多月了,但是我找不到一个能在php和mysql上运行ajax长轮询的准确例子。最好是想找到一个示例ajax长轮询与mysql和codeigniter。
任何人遇到这个问题并有一个很好的例子,请让我知道。
任何阅读这篇文章的人,如果认为他们知道我正在寻找的ajax长投票,请给我发电子邮件或在这里让我知道。我有聊天应用程序几乎完成使用Codeigniter,但我有问题的jquery/ajax长轮询部分,这是客户端。我没有发布这个聊天应用程序,因为上次我发布了另一个聊天应用程序,我这里有另一个开发人员抱怨我发布的代码太多了。我已经准备好将这段代码发送给任何可以提供ajax长轮询代码的人。
非常感谢。
发布于 2012-10-18 09:45:11
我想你应该将聊天消息存储在数据库中??因此,其中一种方法将如下所示:
最重要的是,您需要在第一时间将服务器时间传递给用户,这是获取新聊天消息的关键,所以首先,我们这样做:
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
}
}
} );
}
从"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服务器来测试这段代码。
https://stackoverflow.com/questions/12945292
复制相似问题