Comet(长轮询)和XmlHttpRequest状态

Chr*_*her 5 javascript ajax comet xmlhttprequest long-polling

我正在玩一些原始的XmlHttpRequestObjects + Comet Long Polling.(通常,我会让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()">...
Run Code Online (Sandbox Code Playgroud)

我将longPoll()一个if语句包装起来status > 0,因为我遇到了,当我离开页面时(通过浏览其他地方或重新加载它),最后一个不必要的彗星调用被发送.[在Firefox上,它甚至在进行页面重新加载时会导致严重的问题,由于某些原因我还没有完全理解.]

问题:这是status检查处理此问题的正确方法,还是有更好的解决方案?

Chr*_*her 4

我目前的答案 - 直到被证明是错误的 - 是,解决方案是正确的。