Skip to content

Instantly share code, notes, and snippets.

@cvan
Created February 5, 2014 00:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cvan/8815263 to your computer and use it in GitHub Desktop.
Save cvan/8815263 to your computer and use it in GitHub Desktop.
promise-based, jQuery-like $.post XHR wrapper
function reqResponse(xhr) {
var data = xhr.responseText;
if ((xhr.getResponseHeader('Content-Type') || '').split(';', 1)[0].indexOf('json') !== -1) {
try {
return JSON.parse(data);
} catch(e) {
// Oh well.
return {};
}
}
return data || null;
}
$.post = function(url, params) {
return new Promise(function(resolve, reject) {
params = serialize(params || {});
var xhr = new XMLHttpRequest();
xhr.open('post', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-Length', params.length);
xhr.setRequestHeader('Connection', 'close');
xhr.send(params);
xhr.addEventListener('load', function() {
var res = reqResponse(xhr);
var statusCode = xhr.status;
if (statusCode < 200 || statusCode > 300) {
return reject(res, xhr);
}
return resolve(res, xhr);
}, false);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment