1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| function myAxios(config) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest()
if (config.params) { const paramsObj = new URLSearchParams(config.params) const queryString = paramsObj.toString() config.url += `?${queryString}` } xhr.open(config.method || 'GET', config.url)
xhr.addEventListener('loadend', () => { if (xhr.status >= 200 && xhr.status < 300) { resolve(JSON.parse(xhr.response)) } else { reject(new Error(xhr.response)) } }) if (config.data) { const jsonStr = JSON.stringify(config.data) xhr.setRequestHeader('Content-Type', 'application/json') xhr.send(jsonStr) } else { xhr.send() } }) }
document.querySelector('.reg-btn').addEventListener('click', () => { myAxios({ url: 'http://hmajax.itheima.net/api/register', method: 'POST', data: { username: 'itheima999', password: '666666' } }).then(result => { console.log(result) }).catch(error => { console.dir(error) }) })
|