Skip to content

Instantly share code, notes, and snippets.

@gigonaut
Created January 18, 2012 03:48
Show Gist options
  • Save gigonaut/1630773 to your computer and use it in GitHub Desktop.
Save gigonaut/1630773 to your computer and use it in GitHub Desktop.
xhr request wrapper.
/* Author: Zack Bonebrake
*/
var Requester = function(options) {
this.url = options.url;
this.data = options.data;
this.method = options.reqMethod;
this.cors = options.cors || false;
this.expects = options.expects || 'application/json'
this.headers = options.httpHeaders;
}
Requester.prototype.send = function(data, callback) {
var self = this;
if (XMLHttpRequest) {
var request = new XMLHttpRequest();
if (this.cors && request.withCredentials != undefined) {
request.onreadystatechange = handler;
console.log(self.method);
request.open(self.method, self.url, true);
request.setRequestHeader('Content-Type', self.expects);
var keys = Object.keys(self.headers);
for (var i in keys) {
request.setRequestHeader(keys[i], self.headers[keys[i]]);
}
if (self.data) {
request.send(JSON.stringify(self.data));
} else {
request.send();
}
}
}
function handler() {
if (this.readyState == 4) {
if (this.status >= 300) {
//TODO: make this meaningful
err = new Error('something went wrong: ' + this.status);
callback(err)
} else {
callback(null, this.responseText);
}
}
// console.log(this.readyState);
// console.log(this.responseText);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment