Created
February 28, 2019 07:23
-
-
Save chengjianhua/6ad463c95023b55845a0e0c74e8741f7 to your computer and use it in GitHub Desktop.
simple-ajax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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