[英]Javascript ajax double request
I have a AJAX jQuery chat application, it works by asking for new messages, at the start it just asks for 20 most recent messages, then it gets the count of the latest message, so when it asks again, it knows what the last message ID was, and the server returns message since then. 我有一个AJAX jQuery聊天应用程序,它通过询问新消息来工作,一开始它只询问20条最新消息,然后它获取最新消息的计数,所以当它再次询问时,它知道最后一条消息是什么ID是,然后服务器返回消息。
The issue is on slower connections, it takes longer then the rate it requests, resulting in getting more then one of the same message because there are more then one request running with the same old message ID. 问题在于连接速度较慢,它需要的时间比它请求的速率要长,导致获得多个相同的消息,因为有多个请求以相同的旧消息ID运行。
How would I make sure it only is running one request at a time? 我如何确保它一次只运行一个请求?
I presume you are using setInterval
to do your repeated requests. 我假设您正在使用
setInterval
来执行重复请求。 This isn't best practice, for the exact reason you mention: if a function takes a long time, a new one may take place before the previous iteration had completed. 这不是最佳实践,因为您提到的确切原因:如果函数需要很长时间,则可能会在上一次迭代完成之前发生新函数。
It is best to use setTimeout
within the complete
handler of your post
call: 最好在
post
调用的complete
处理程序中使用setTimeout
:
function doRequest() {
$.ajax({
url: 'someurl',
/* some other options */
complete: function(){
setTimeout(doRequest, 30000);
}
});
}
doRequest();
Use a setTimeout
in the onreadystatechange
event handler ( success
and error
in jQuery terms IIRC) to fire off the 'next' request. 在
onreadystatechange
事件处理程序中使用setTimeout
(jQuery术语IIRC中的success
和error
)来触发“下一个”请求。 Don't use setInterval
and send them out on a timer regardless. 无论如何都不要使用
setInterval
并将它们发送出去。
What about a re-entrant function? 重入函数怎么样? Something like:
就像是:
function getMessages(){
$.get('url', function(data){
//process the data
getMessages();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.