Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comet (long polling) and XmlHttpRequest status

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?

like image 714
Chris Lercher Avatar asked Apr 12 '10 19:04

Chris Lercher


1 Answers

My current answer - until proven false - is, that the solution is correct.

like image 80
Chris Lercher Avatar answered Sep 21 '22 11:09

Chris Lercher