Created
February 5, 2014 00:33
-
-
Save cvan/8815263 to your computer and use it in GitHub Desktop.
promise-based, jQuery-like $.post XHR wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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