ajax long 不对,AJAX long-polling:我如何让这段代码长时间投票?

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();

}

2014-06-20

Mark

+0

[**'setInterval' **](https://developer.mozilla.org/ en/docs/Web/API/window.setInterval)但是你应该看看[** Web Sockets **](http://www.html5rocks.com/en/tutorials/websockets/basics/) –

+0

@Darren你的意思是我应该只是将setTimeout更改为setInterval?顺便说一句,我不使用旧的浏览器兼容性问题的网络套接字。我也不使用nodejs,因为我的共享服务器不允许长时间运行的进程。 –

+0

这个快速[** JSFiddle **](http://jsfiddle.net/WyS2W/2/)演示说明了setInterval(检查控制台)。或者你应该看看[** This SO Answer **](http://stackoverflow.com/a/1086448/2518525) –