在我了解長輪詢之前,我有這個代碼:
var updateMessages = function() {
var conv_id = [];
var lastMessages = [];
$('.user').each(function(){
conv_id.push($(this).find('p').attr('id'));
});
if($('.rightP').find('.msg .msg_block').length!=0){
$('.rightP').find('.msg .msg_block').each(function(){
if(($('.rightP').find('.msg .msg_block p').length)==0){
}else {
lastMessages.push($(this).find('p:last-child')[0].dataset.created_at);
}
});
}
$.ajax({
type: "POST",
url: 'create/populate',
data: {
'from': lastMessages,
'conv_id':conv_id
},
success: function(messages) {
console.log(messages);
$.each(messages, function() {
appendMessage(this);
});
},
error: function(xhr,textStatus,errorThrown) {
console.log(xhr.responseText);
},
complete: function() {
window.setTimeout(updateMessages, 2000);
},
dataType: 'json'
});
};
updateMessages();
然而,有人評論此代碼不是長輪詢。是以我研究并調整了上面的一些代碼:
...
complete: function() {
updateMessages(); //also tried updateMessages;
},
timeout:30000,
dataType: 'json'
...
但它遇到了諸如根本不輪詢的問題,并且消息不會更新。如何調整原始代碼進行長輪詢?改進代碼是一個獎勵。謝謝!
gente note:我不使用遺留浏覽器相容性問題的網絡套接字bcoz。我也不使用nodejs,因為我的共享伺服器不允許長時間運作的程序。
PHP代碼(在我的控制器中)
public function index()
{
$timestamps = Input::get('from'); //timestamp of latest message
$conv_id = Input::get('conv_id');
$allMessages = Messages::whereIn('conv_id',$conv_id);
if(is_null($timestamps)){
$messages = $allMessages->orderBy('created_at','desc')->take(10);
}else{
asort($timestamps);
$messages = $allMessages->where('created_at','>',end($timestamps));
}
return $messages->get()->reverse();
}