Skip to content

Instantly share code, notes, and snippets.

@krishna19
Forked from hsnaydd/es6-ajax-request.js
Created January 4, 2018 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krishna19/23fd50dd912e73cfbf577c349ca89d94 to your computer and use it in GitHub Desktop.
Save krishna19/23fd50dd912e73cfbf577c349ca89d94 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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment