Skip to content

Instantly share code, notes, and snippets.

@chakhsu
Created May 7, 2017 05:11
Show Gist options
  • Save chakhsu/163d7b02e18e1cacb7ce59d9cf65b8fc to your computer and use it in GitHub Desktop.
Save chakhsu/163d7b02e18e1cacb7ce59d9cf65b8fc to your computer and use it in GitHub Desktop.
[Ajax] #JavaScript #Ajax
export function get(url) {
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.send(null);
xhr.addEventListener('readystatechange', function () {
if (xhr.readyState === 4 && xhr.status === 200) {
try {
const data = JSON.parse(xhr.responseText);
resolve(data);
} catch (e) {
reject(e);
}
}
});
xhr.addEventListener('error', function (e) {
reject(error);
});
});
}
export function post(url) {
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.open('post', url);
xhr.send(null);
xhr.addEventListener('readystatechange', function () {
if (xhr.readyState === 4 && xhr.status === 200) {
try {
const data = JSON.parse(xhr.responseText);
resolve(date);
} catch (e) {
reject(e);
}
}
});
xhr.addEventListener('error', function (e) {
reject(error);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment