Created
January 19, 2012 20:27
-
-
Save cameronism/1642384 to your computer and use it in GitHub Desktop.
XHR and JSON is all you really need
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(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