Skip to content

Instantly share code, notes, and snippets.

@hayes
Last active December 25, 2015 15:29
Show Gist options
  • Save hayes/6998883 to your computer and use it in GitHub Desktop.
Save hayes/6998883 to your computer and use it in GitHub Desktop.
simple request function
function request(method, path, body, headers, ready) {
var xhr = new XMLHttpRequest
, zone
if(typeof headers === 'function') {
ready = headers
headers = {}
} else if(typeof body === 'function') {
ready = body
body = null
}
headers = headers || {}
xhr.onreadystatechange = on_state_change(xhr, ready)
xhr.open(method, path, true)
for(var key in headers) {
xhr.setRequestHeader(headers[key])
}
xhr.send(body || null)
return xhr
}
function on_state_change(xhr, done) {
return function() {
var parsed
if(xhr.readyState !== 4) {
return
}
var is_json = /json/.test(xhr.getResponseHeader('Content-Type')) ||
/json/.test(xhr.getResponseHeader('content-type'))
try {
if(xhr.status < 200 || xhr.status > 299) {
throw new Error('xhr ' + xhr.status + ' ' + xhr.responseText)
}
parsed =
xhr.responseType ? xhr.response :
is_json ? JSON.parse(xhr.responseText) :
xhr.responseText
} catch(e) {
e.xhr = xhr
return done(e)
}
done(null, parsed)
}
}
@hayes
Copy link
Author

hayes commented Oct 15, 2013

request(String:method, String:path, [Object:headers, [String:body,]] Function:ready) -> xhr

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment