Created
January 2, 2012 21:04
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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