Problem with long polling with JQuery on Tomcat Server
-
25-09-2019 - |
Question
I created a CometServlet according to this example http://tomcat.apache.org/tomcat-7.0-doc/aio.html. Then I tried to get data from it using JQuery. The code is following:
$(function() {
$.longPoll = function(url, success, error) {
$.ajax({
url : url,
success: function(data, status) {
$.longPoll(url, success, error);
if (success) {
success(data, status);
}
},
error: function(data, status) {
$.longPoll(url, success, error);
if (error) {
error(data, status);
}
}
});
};
$.longPoll("./comet", "", function(data, status) {
alert("success:" + data);
}, function(data, status) {
alert("error:" + data);
});
});
The problem is that the success function doesn't trigger (even though I can see in the FireBug console that the data comes). I think it happens because the server doesn't close a response writer, but it is a goal of the long-polling :)
Does any one have any ideas how it can be solved?
Solution 2
The problem solution is to add timer for checking the long-poll stream for a new data. Great explanation is here: http://www.bennadel.com/blog/1976-Long-Polling-Experiment-With-jQuery-And-ColdFusion.htm
Thanks everyone.
OTHER TIPS
You need to overwrite the xhr onreadystatechange
in order to check for readyState === 3
with jQuery .ajax()
. Example:
var xhr = $.ajax({});
xhr._onreadystatechange = xhr.onreadystatechange; // save original handler
xhr.onreadystatechange = function() {
xhr._onreadystatechange(); // execute original handler
if (xhr.readyState === 3) alert('Interactive');
};