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 e开发者_开发技巧ven 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?
My current answer - until proven false - is, that the solution is correct.
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
精彩评论