Skip to content

Instantly share code, notes, and snippets.

@hsnaydd
Created March 7, 2016 11:52
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save hsnaydd/0d6061a8801222ccf0e6 to your computer and use it in GitHub Desktop.
Save hsnaydd/0d6061a8801222ccf0e6 to your computer and use it in GitHub Desktop.
Es6 Ajax request
export default class Ajax {
get(url, callback) {
let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('GET', url);
xhr.onreadystatechange = () => {
if (xhr.readyState > 3 && xhr.status === 200) {
callback(xhr.responseText);
}
};
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send();
return xhr;
}
post(url, data, callback) {
let params = typeof data == 'string' ? data : Object.keys(data).map((k) => {
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]);
}).join('&');
let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open('POST', url);
xhr.onreadystatechange = function() {
if (xhr.readyState > 3 && xhr.status === 200) {
callback(xhr.responseText);
}
};
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(params);
return xhr;
}
}
@rolandhegedus
Copy link

rolandhegedus commented Jul 20, 2017

hey! I think it would be nice if you'd use promises aswell :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment