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?
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); });
}});
You need to poll server multiple times or use a socket connection like socket.io . I reccomend reading this article .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.