Reputation: 2119
I'm trying to do some long polling and I'm having a hard time figuring out how I can read data from the server as it gets sent.
I have the following on the client:
var xhr = $.ajax('/getData');
setInterval(function(){
console.log(xhr.responseText);
}, 1000); // reads response each 1s
The server
app.get('/getData', function(req, res){
setInterval(function(){
res.write('hi-' + Math.random()); // write random stuff each 1s
}, 1000);
});
But xhr.responseText
only gets populated when the request finishes.
Is this even possible to do? I have to make a new request for /getData
every time I need something? I can't take advantages of the same request?
Upvotes: 0
Views: 48
Reputation: 1
You need to poll server multiple times or use a socket connection like socket.io. I reccomend reading this article.
Upvotes: 0
Reputation: 7169
Please read about onreadystatechange
http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
$.ajax({
// ...
beforeSend: function (request, settings) {
$(request).bind("readystatechange", function (e) { alert("changed " + e.target.readyState); });
}});
Upvotes: 1