Skip to content

Instantly share code, notes, and snippets.

@doug
Created October 11, 2012 18:38
Show Gist options
  • Save doug/3874604 to your computer and use it in GitHub Desktop.
Save doug/3874604 to your computer and use it in GitHub Desktop.
simple http request for json
// Do checks for minimum requirements
if (!XMLHttpRequest || !JSON) {
throw Error('Browser does not support the minimum requirements of ' +
'XMLHttpRequest, JSON' +
'. Try adding modernizer to polyfill.');
}
function http(method, url, data, success) {
var r = new XMLHttpRequest();
r.open(method, url, true);
r.onreadystatechange = function() {
if (r.readyState == 4) {
var resp = JSON.parse(r.responseText);
if (resp && resp.error) {
throw new Error(resp.error);
return;
}
if (success) {
success(resp);
}
}
};
r.setRequestHeader('Content-Type', 'application/json');
if (data) {
switch (toString.call(data)) {
case '[object Object]':
data = JSON.stringify(data);
break;
// case '[object String]':
// break;
// case '[object FormData]':
// break;
}
}
r.send(data);
}
http.GET = function(url, success) { http('GET', url, null, success); };
http.POST = function(url, data, success) { http('POST', url, data, success); };
http.DELETE = function(url, success) { http('DELETE', url, null, success); };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment