Skip to content

Instantly share code, notes, and snippets.

@RB-Lab
Forked from aaronbjork/simple-ajax.js
Last active January 31, 2016 17:17
Show Gist options
  • Save RB-Lab/e95e0880bfc86debbff7 to your computer and use it in GitHub Desktop.
Save RB-Lab/e95e0880bfc86debbff7 to your computer and use it in GitHub Desktop.
function encodeAsUrl_(params){
return Object.keys(params).map(key => key + '=' + params[key]).join('&')
}
function handleResponce_(xhr, cb, errcb){
return function () {
if (4 === xhr.readyState) {
if(xhr.status >= 200 && xhr.status < 400){
cb(xhr);
} else {
errcb(xhr);
}
}
}
}
function get(url, cb, errcb) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = handleResponce_(xhr, cb, errcb);
xhr.send();
}
function post(url, params, cb, errcb){
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onreadystatechange = handleResponce_(xhr, cb, errcb);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(encodeAsUrl(params));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment