From ce60becc50e2f78f21519204d90f9666f43d725f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E6=99=BA=E7=BF=94?= <2045602860@qq.com> Date: Wed, 13 Dec 2023 02:19:58 +0000 Subject: [PATCH] =?UTF-8?q?34=20=E5=88=98=E6=99=BA=E7=BF=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 刘智翔 <2045602860@qq.com> --- .../Ajax\345\260\201\350\243\205.md" | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 "34 \345\210\230\346\231\272\347\277\224/Ajax\345\260\201\350\243\205.md" diff --git "a/34 \345\210\230\346\231\272\347\277\224/Ajax\345\260\201\350\243\205.md" "b/34 \345\210\230\346\231\272\347\277\224/Ajax\345\260\201\350\243\205.md" new file mode 100644 index 0000000..67ebe23 --- /dev/null +++ "b/34 \345\210\230\346\231\272\347\277\224/Ajax\345\260\201\350\243\205.md" @@ -0,0 +1,37 @@ +# 笔记 + +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 +}) +``` \ No newline at end of file -- Gitee