Skip to content

Instantly share code, notes, and snippets.

@bjoerge
Created May 13, 2012 21:50
Show Gist options
  • Save bjoerge/2690398 to your computer and use it in GitHub Desktop.
Save bjoerge/2690398 to your computer and use it in GitHub Desktop.
Cross browser xmlhttprequest get
# Cross browser xmlhttprequest function (based on http://www.quirksmode.org/js/xmlhttp.html)
xhrGet = do ->
XMLHttpFactories = [
-> new XMLHttpRequest()
-> new ActiveXObject("Msxml2.XMLHTTP")
-> new ActiveXObject("Msxml3.XMLHTTP")
-> new ActiveXObject("Microsoft.XMLHTTP")]
createXHR = ->
xhr = null
for factory in XMLHttpFactories
if (try xhr = factory())
createXHR = -> factory() # memoize the factory that worked
break
xhr
(url) ->
xhr = createXHR()
deferred = new Deferred()
return unless xhr
xhr.open("GET", url, true)
xhr.onreadystatechange = ->
return unless xhr.readyState == 4
success = 200 <= xhr.status < 300 || xhr.status == 304
deferred[if success then 'resolve' else 'reject'](xhr.responseText)
xhr.send()
deferred
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment