Created
January 22, 2014 14:53
-
-
Save thealscott/8560049 to your computer and use it in GitHub Desktop.
XHR ajax snippet (via Remy)
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 request(type, url, opts, callback) { | |
var xhr = new XMLHttpRequest(), | |
fd; | |
if (typeof opts === 'function') { | |
callback = opts; | |
opts = null; | |
} | |
xhr.open(type, url); | |
if (type === 'POST' && opts) { | |
fd = new FormData(); | |
for (var key in opts) { | |
fd.append(key, JSON.stringify(opts[key])); | |
} | |
} | |
xhr.onload = function () { | |
callback(JSON.parse(xhr.response)); | |
}; | |
xhr.send(opts ? fd : null); | |
} | |
var get = request.bind(this, 'GET'); | |
var post = request.bind(this, 'POST'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment