Skip to content

Instantly share code, notes, and snippets.

@bjoerge
Created January 2, 2012 21:04
Show Gist options
  • Save bjoerge/1552115 to your computer and use it in GitHub Desktop.
Save bjoerge/1552115 to your computer and use it in GitHub Desktop.
A simple example that polls for new data in a streamed http response.
var xhr = function (url, options) {
options = options || {};
var req = new XMLHttpRequest(),
method = options.method || 'get',
dfd = new $.Deferred();
req.open(method, url, true);
req.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
var last = function (arr) {
return arr[arr.length - 1];
};
req.onreadystatechange = function () {
if (req.readyState == 3) {
dfd.notify(last($.trim(req.responseText).split("\n")));
}
else if (req.readyState == 4) {
if ((/^[20]/).test(req.status)) dfd.resolve(req);
if ((/^[45]/).test(req.status)) req.reject(req);
}
};
req.send();
return dfd;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment