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?
status > 0
. After all, theonreadystatechange
function will only be called withreadyState == 4
when a request completes. How did you see that "one last unnecessary comet call is sent"? And what severe problems in Firefox are you talking about? Perhaps the test case in another answer is helpful to you (with jQuery, but it's essentially the same): https://mcmap.net/q/464638/-chrome-39-s-loading-indicator-keeps-spinning-during-xmlhttprequest/… – Snowyonreadystatechange
always gets called when leaving the page. It hasreadyState == 4
, but astatus == 0
. It's easy to see that by inserting a simplealert(...)
But I don't know, if this is standard behaviour (that's part of my question.) – Penoyerif (xhr.status > 0)
, then after the page reload, the first Ajax call doesn't work at all. It's as if it collides with the last Ajax call that gets issued milliseconds before the page reload. – Penoyer