Skip to content

Instantly share code, notes, and snippets.

@chengjianhua
Created February 28, 2019 07:23
Show Gist options
  • Save chengjianhua/6ad463c95023b55845a0e0c74e8741f7 to your computer and use it in GitHub Desktop.
Save chengjianhua/6ad463c95023b55845a0e0c74e8741f7 to your computer and use it in GitHub Desktop.
simple-ajax
function ajax(url: string, { method = 'GET', data = undefined } = {}) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
if (method === 'POST') {
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
}
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 400) {
resolve(parseJson(xhr.responseText));
} else {
reject({ code: xhr.status, message: xhr.responseText }); // eslint-disable-line
}
};
xhr.onerror = reject;
xhr.send(JSON.stringify(data));
});
}
function parseJson(str) {
try {
return JSON.parse(str);
} catch (e) {
return str;
}
}
export default ajax;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment