Reputation: 4793
I am trying to wite a simple long polling system (yep, I do not want to use any ready-made scipt, as I want to learn from it). I am using a node server where I can easily pipe/write my data back to the client without calling result.end();
. How should I do this client side? I just want this as a simple and not really good fallback for users using ie<=9, as the better browsers get a fast and easy to use websocket.
Long question short: How to do long-polling in plain JS without jQuery or other framework? (Or is there a better way than long-polling).
Upvotes: 3
Views: 5574
Reputation: 8580
Is the following what you are looking for?
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';//or 'text', 'json', ect. there are other types.
xhr.timeout = 60000;//milliseconds until timeout fires. (1 minute)
xhr.onload = function(e2){
var blob = xhr.response;
//handle response data
}
xhr.ontimeout = function(){
//if you get this you probably should try to make the connection again.
//the browser should've killed the connection.
}
xhr.open('GET', "/path/to/URL.cmd?param1=val1¶m2=val2", true);
xhr.send();
I think the timeout
attribute is the key to making the long-polls work, for more see the spec there are more information on the responseType's in the same document. If timeout is not specified, it's default value is zero.
Upvotes: 2