Last active
December 25, 2015 15:29
-
-
Save hayes/6998883 to your computer and use it in GitHub Desktop.
simple request function
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
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
request(String:method, String:path, [Object:headers, [String:body,]] Function:ready) -> xhr