diff --git "a/01 \351\231\210\346\242\246\346\242\246/20231213 Ajax\350\207\252\345\267\261\345\260\201\350\243\205\344\270\200\344\270\252axios.md" "b/01 \351\231\210\346\242\246\346\242\246/20231213 Ajax\350\207\252\345\267\261\345\260\201\350\243\205\344\270\200\344\270\252axios.md" new file mode 100644 index 0000000000000000000000000000000000000000..9aa8635ad99641465f8794c0c4165374e0c93bed --- /dev/null +++ "b/01 \351\231\210\346\242\246\346\242\246/20231213 Ajax\350\207\252\345\267\261\345\260\201\350\243\205\344\270\200\344\270\252axios.md" @@ -0,0 +1,35 @@ +/** + * 目标:封装_简易axios函数_获取省份列表_ + * 1. 定义axios函数,接收配置对象,返回Promise对象 + * 2. 发起XHR请求,默认请求方法为GET + * 3. 调用成功/失败的处理程序 + * 4. 使用axios函数,获取省份列表展示 +*/ +// 1. 定义axios函数,接收配置对象,返回Promise对象 +function axios(config) { + return new Promise((resolve, reject) => { + // 2. 发起XHR请求,默认请求方法为GET + const XML= new XMLHttpRequest() + XML.open(config.method || 'GET', config.url) + XML.addEventListener('loadend', () => { + // 3. 调用成功/失败 + if ( XML.status >= 200 && XML.status < 300) { + resolve(JSON.parse( XML.response)) + } else { + reject(new Error( XML.response)) + } + }) + XML.send() + }) +} + +// 4. 使用axios函数,获取省份列表展示 +axios({ + url: 'http://hmajax.itheima.net/api/province' +}).then(result => { + console.log(result) + document.querySelector('.my-p').innerHTML = result.list.join('
') +}).catch(error => { + console.log(error) + document.querySelector('.my-p').innerHTML = error.message +}) \ No newline at end of file