Comet(长轮询)和 XmlHttpRequest 状态
我正在尝试使用原始 XmlHttpRequestObjects + Comet 长轮询。 (通常,我会让 GWT 或其他框架为我处理这个问题,但我想了解更多相关信息。)
我编写了以下代码:
function longPoll() {
var xhr = createXHR(); // Creates an XmlHttpRequestObject
xhr.open('GET', 'LongPollServlet', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
...
}
if (xhr.status > 0) {
longPoll();
}
}
}
xhr.send(null);
}
...
<body onload="javascript:longPoll()">...
我将 longPoll()
调用包装在 if 中检查 status > 的语句0
,因为我遇到过,当我离开页面(通过浏览其他地方,或重新加载它)时,会发送最后一个不必要的彗星调用。 [在 Firefox 上,它甚至会在重新加载页面时导致严重问题,由于某种原因我还不完全理解。]
问题:这是状态吗?
检查处理这个问题的正确方法,或者有更好的解决方案吗?
I'm playing around a little bit with raw XmlHttpRequestObjects + Comet Long Polling. (Usually, I'd let GWT or another framework handle of this for me, but I want to learn more about it.)
I wrote the following code:
function longPoll() {
var xhr = createXHR(); // Creates an XmlHttpRequestObject
xhr.open('GET', 'LongPollServlet', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
...
}
if (xhr.status > 0) {
longPoll();
}
}
}
xhr.send(null);
}
...
<body onload="javascript:longPoll()">...
I wrapped the longPoll()
call in an if statement that checks for status > 0
, because I encountered, that when I leave the page (by browsing somewhere else, or by reloading it), one last unnecessary comet call is sent. [And on Firefox, it even causes severe problems when doing a page reload, for some reason I don't fully understand yet.]
Question: Is that status
check the correct way to handle this problem, or is there a better solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我目前的答案 - 直到被证明是错误的 - 是,解决方案是正确的。
My current answer - until proven false - is, that the solution is correct.
我喜欢这个循环的简单性......我认为服务器端脚本必须休眠或至少循环,直到它在考虑长轮询之前获取新数据,尽管这只是正常轮询。我还会添加一些内容来检查请求是否失败。将其包装在 try catch bloch 中应该可以解决问题
i like the simplicity of this loop.... i think the server side script has to sleep or atleast loop until it gets new data before its considered long polling though this is just normal polling. i would also add something to check if the reques fails though. wrapping that in a try catch bloch should do the trick