Skip to content

Instantly share code, notes, and snippets.

@lightsofapollo
Created April 24, 2012 19:58
Show Gist options
  • Select an option

  • Save lightsofapollo/2483148 to your computer and use it in GitHub Desktop.

Select an option

Save lightsofapollo/2483148 to your computer and use it in GitHub Desktop.
xhr wrapper (modern browsers only)
/**
* Make an XHR request accepts the following options
*
* method: (String) GET, POST, etc..
* url: (String) http://...
* async: (Boolean)
* success: (Callback) fired on success (get xhr object)
* error: (Callback) fired on error (get xhr object)
* complete: (Callback) fired on both error and success (gets xhr object)
* headers: (Object) list of headers
* data: (Object) sent data
*
* @param {Object} options
*/
function request(options){
var xhr = new XMLHttpRequest(),
header;
if(typeof(options) === 'undefined'){
options = {};
}
function cb(type){
if(options[type]){
options[type](xhr);
}
}
xhr.open(options.method || 'GET', options.url, options.async || true);
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status === 200){
cb('success');
cb('complete');
} else {
cb('error');
cb('complete');
}
}
};
if(options.headers){
for(header in options.headers){
if(options.headers.hasOwnProperty(header)){
xhr.setRequestHeader(header, options.headers[header]);
}
}
}
xhr.send(options.data || null);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment