Skip to content

Instantly share code, notes, and snippets.

@cameronism
Created January 19, 2012 20:27
Show Gist options
  • Save cameronism/1642384 to your computer and use it in GitHub Desktop.
Save cameronism/1642384 to your computer and use it in GitHub Desktop.
XHR and JSON is all you really need
(function(context) {
var xhr = context.XMLHttpRequest,
json = context.JSON,
mime = 'application/json';
context.xhr = xhr && json && function(method, url, data, callback) {
var req = new xhr();
req.onreadystatechange = function() {
if(req.readyState == 4) {
var status = req.status,
body,
err;
try {
if (status > 0) {
body = req.responseText;
body = body ? json.parse(body) : err;
} else {
err = req;
}
}
catch (e) {
err = e;
}
if (callback) {
callback(err, status, body);
callback = null;
}
req.onreadystatechange = null;
}
};
req.open(method, url, true);
req.setRequestHeader('Accept', mime);
req.setRequestHeader('Content-Type', mime);
//req.withCredentials = true;
req.send(data ? json.stringify(data) : null);
};
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment