Skip to content

Instantly share code, notes, and snippets.

@s-melnikov
Created March 17, 2016 06:08
Show Gist options
  • Save s-melnikov/22d9b7c54e2a356ea1f2 to your computer and use it in GitHub Desktop.
Save s-melnikov/22d9b7c54e2a356ea1f2 to your computer and use it in GitHub Desktop.
function request(method, url, data, callback) {
var xhttp = new XMLHttpRequest()
xhttp.open(method, url, true)
xhttp.setRequestHeader("Content-type", "application/json")
if (callback) {
xhttp.onload = function() {
if (xhttp.status >= 200 && xhttp.status < 400) {
try {
callback(null, JSON.parse(xhttp.responseText))
} catch(e) {
callback({type: "parse", text: e})
}
} else {
callback({type: "status", text: xhttp.status})
}
}
xhttp.onerror = function(e) {
callback({type: "error", text: e})
}
}
xhttp.send(data && JSON.stringify(data) || null)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment