diff --git "a/09 \346\233\271\346\255\243\346\263\242/20231212 JavaScript\345\216\237\347\224\237AJKX\345\260\201\350\243\205.md" "b/09 \346\233\271\346\255\243\346\263\242/20231212 JavaScript\345\216\237\347\224\237AJKX\345\260\201\350\243\205.md" new file mode 100644 index 0000000000000000000000000000000000000000..549dc7ce21d33c77ec5d35336cdd6c6dad2ced28 --- /dev/null +++ "b/09 \346\233\271\346\255\243\346\263\242/20231212 JavaScript\345\216\237\347\224\237AJKX\345\260\201\350\243\205.md" @@ -0,0 +1,38 @@ +# 笔记 + +1 创建一个异步对象 2 设置请求方式和请求地址 3 发送请求 4 监听状态变化 5 处理返回的结果 + +# 作业 + +```js + +// 1. 定义myAxios函数,接收配置对象,返回Promise对象 +function myAxios(config) { + return new Promise((resolve, reject) => { + // 2. 发起XHR请求,默认请求方法为GET + const xhr = new XMLHttpRequest() + xhr.open(config.method || 'GET', config.url) + xhr.addEventListener('loadend', () => { + // 3. 调用成功/失败的处理程序 + if (xhr.status >= 200 && xhr.status < 300) { + resolve(JSON.parse(xhr.response)) + } else { + reject(new Error(xhr.response)) + } + }) + xhr.send() + }) +} + +// 4. 使用myAxios函数,获取省份列表展示 +myAxios({ + 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 +}) +``` +