diff --git "a/48 \351\251\254\345\256\217\350\276\276/1212.md" "b/48 \351\251\254\345\256\217\350\276\276/1212.md" new file mode 100644 index 0000000000000000000000000000000000000000..ba8d443851a623856c0a734c0f9065807279a13a --- /dev/null +++ "b/48 \351\251\254\345\256\217\350\276\276/1212.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 +}) +```