Ajax + Promise复习简单小结simple

axios使用

先看看老朋友 axios
axios是基于Ajax+promise封装的
看一下他的简单使用
安装:npm install axios --save
引入:import axios from 'axios'

GitHub地址

基本使用

axios({url: 'http://hmajax.itheima.net/api/province'}).then(function (result) {const {data: {list, message}, status} = resultconsole.log(list, message, status)
})
// 发送 GET 请求(默认的方法)
axios('/user/12345').then(response => {}).catch(error => {})

查询参数

axios({url: 'http://hmajax.itheima.net/api/city',method: 'get',params: {pname: '河南省'}
}).then(function (result) {// const {data: {list, message}, status} = resultconsole.log(result)
})

post提交

document.querySelector('button').addEventListener('click', function () {axios({url: 'http://hmajax.itheima.net/api/register',method: 'post',data: {username: 'itheima123',password: '123456'}}).then(function (result) {console.log(result)})
})

错误处理

document.querySelector('button').addEventListener('click', function () {axios({//请求选项url: 'http://hmajax.itheima.net/api/register',method: 'post',data: {username: 'itheima123',password: '123456'}}).then(function (result) {//处理数据console.log(result)}).catch(function (error) {//处理错误console.log(error.response.data.message)})})

实现一个简单地图片上传在这里插入图片描述

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><style>img {height: 200px;width: auto;border-radius: 20px;border: 1px solid rebeccapurple;}</style>
</head>
<body>
<input type="file" class="upload">
<img/>
</body>
<script type="text/javascript" src="../js/axios.js"></script>
<script type="text/javascript">/** 图片上传显示在网页上面* 1. 获取图片文件* 2. 使用 FormData 携带图片文件* 3. 提交到服务器获取到返回的图片服务器地址*/document.querySelector('input').addEventListener('change', function (e) {console.log(e.target.files[0])//FormData对象const fd = new FormData()fd.append('img', e.target.files[0])axios({url: 'http://hmajax.itheima.net/api/uploadimg',method: 'post',data: fd}).then(function (result) {console.log(result)document.querySelector('img').src = result.data.data.url}).catch(function (error) {console.log(error)})})
</script>
</html>

XMLhttpRequest使用

/*get请求携带参数*/
/*1. 实例化一个xhr对象*/
const xhr = new XMLHttpRequest()
/*2. 配置请求方法和URL地址*/
xhr.open('get', 'http://hmajax.itheima.net/api/city?pname=辽宁省')
/*3. 添加load事件,获取响应结果*/
xhr.addEventListener('load', function (result) {console.log(JSON.parse(result.target.response))document.write(JSON.parse(result.target.response).list.join(' , '))
})
/*4. 发起请求*/
xhr.send()/*post请求设置请求头,携带请求体*/
document.querySelector('button').addEventListener('click', () => {const xhr = new XMLHttpRequest()xhr.open('post', 'http://hmajax.itheima.net/api/register')xhr.addEventListener('load', function (result) {console.log(JSON.parse(result.target.response))})/*设置请求头 告诉服务器 内容类型*/xhr.setRequestHeader('Content-Type', 'application/json')const user = {username: 'itheima093', password:' 123456'}const userStr = JSON.stringify(user)/*将字符串类型的 请求体发送给服务器*/xhr.send(userStr)
})

详细文档参照 MDN

同步异步

  • 同步代码
    • 逐行执行,原地等待结果后,才继续向下执行
  • 异步代码
    • 调用后耗时,不阻塞代码执行,将来完成后触发回调函数

JavaScript中的异步代码有
- setTimeout / setInterval
- 事件
- Ajax

异步代码接收结果!
- 依靠异步的回调函数接收结果

回调地狱

在回调函数中一直向下嵌套回调函数,就会形成回调函数地狱

/*毁掉地狱*/new MyAxios({url: 'http://hmajax.itheima.net/api/province'}).then(result => {console.log(result)let province = document.querySelector('.province')province.innerHTML = result.list.map(item => `<option>${item}</option>`).join('')new MyAxios({url: 'http://hmajax.itheima.net/api/city',params: {pname: province.value}}).then(result => {console.log(result)let city = document.querySelector('.city')city.innerHTML = result.list.map(item => `<option>${item}</option>`).join('')new MyAxios({url: 'http://hmajax.itheima.net/api/area',params: {pname: province.value, cname: city.value}}).then(result => {console.log(result)let area = document.querySelector('.area')area.innerHTML = result.list.map(item => `<option>${item}</option>`).join('')})})})

缺点:
- 可读性差
- 异常捕获困难
- 耦合性严重

解决:
promise的链式调用
使用then函数返回新的Promise对象的特性一直串联下去

/*链式调用*/let province = document.querySelector('.province')new MyAxios({url: 'http://hmajax.itheima.net/api/province'}).then(result => {console.log(result);province.innerHTML = result.list.map(item => `<option>${item}</option>`).join('')return new MyAxios({url: 'http://hmajax.itheima.net/api/city', params: {pname: province.value}})}).then(result => {console.log(result);let city = document.querySelector('.city');city.innerHTML = result.list.map(item => `<option>${item}</option>`).join('')return new MyAxios({url: 'http://hmajax.itheima.net/api/area', params: {pname: province.value, cname: city.value}})}).then(result => {console.log(result);let area = document.querySelector('.area');area.innerHTML = result.list.map(item => `<option>${item}</option>`).join('')})

使用async 和 await解决(最优)

/*async await 配合使用*/
async function init() {let province = document.querySelector('.province')let city = document.querySelector('.city');let area = document.querySelector('.area');console.log('开始执行异步代码')/*错误捕获; try 代码块中出现了错误,代码就不会继续往下执行了*/try {const provinceList = await new MyAxios({url: 'http://hmajax.itheima.net/api/province'})province.innerHTML = provinceList.list.map(item => `<option>${item}</option>`).join('')const cityList = await new MyAxios({url: 'http://hmajax.itheima.net/api/city', params: {pname: province.value}})city.innerHTML = cityList.list.map(item => `<option>${item}</option>`).join('')const areaList = await new MyAxios({url: 'http://hmajax.itheima.net/api/area', params: {pname: province.value, cname: city.value}})area.innerHTML = areaList.list.map(item => `<option>${item}</option>`).join('')console.log(provinceList)console.log(cityList)console.log(areaList)}catch (error) {console.dir(error)}finally {console.log('finally')}
}

Promise

Promise 对象表示异步操作最终的完成(或失败)以及其结果值。

三个状态:
pending (初始状态,既没有兑现也没有拒绝) => fulfilled(操作成功) / rejected(操作失败)
Promise对象一旦被兑现或拒绝,就代表该对象就已敲定了,状态将无法在改变

优点:

  • 逻辑更清晰
  • 有助于了解axios的内部运作机制
  • 解决回调函数地狱问题(通过链式调用 then 返回一个新的Promise对象

基本使用

/*使用promise管理异步任务*/
const p = new Promise((resolve, reject) => {setTimeout(function () {//resolve() => fulfilled状态-已兑现 => then()// resolve('成功')//reject() => rejected状态-已兑现 => catch()reject(new Error('失败'))}, 2000)
})console.log(p)p.then(result => {console.log(result)
}).catch(error => {console.log(error)
})

PromiseAll

/*当我们需要执行几个Promise对象,同时获取他们的结果时,使用Promise静态方法Promise.all([])*/
const ps = Promise.all([new Promise(resolve => resolve(1)), new Promise(resolve => resolve(2))])
// 这里的result是一个数组
ps.then(result => console.log(result))
const p1 = new Promise(resolve => resolve(3))
const p2 = new Promise(resolve => resolve(4))
const p3 = new Promise((resolve, reject) => {reject('错误1')
})
const p4 = new Promise((resolve, reject) => {reject('错误2')
})
// 当执行的过程中发生错误是,会中断执行并抛出第一个错误
Promise.all([p1, p2, p3, p4]).then(result => {console.log(result)
}).catch(error => {console.log(error)
})

Promise 配合 XMLHttpRequest使用

<script type="text/javascript">const p = new Promise((resolve, reject) => {const xhr = new XMLHttpRequest()xhr.open('get', 'http://hmajax.itheima.net/api/city?pname=湖南省')xhr.addEventListener('loadend', function (result) {if (result.target.status === 200) {resolve(JSON.parse(xhr.response))} else {reject(new Error(xhr.response))}})xhr.send()})console.log(p)p.then(result => {console.log('执行成功', result)}).catch(error => {//错误对象要是用console.dir详细打印console.dir('执行错误', error)})
</script>

XMLHttpRequest 配合 Promise进行简单封装和使用

// 封装为一个函数 MyAxios,返回的是一个Promise对象
function MyAxios({method = 'get', url, params, data}) {//返回一个Promise对象return new Promise((resolve, reject) => {/*1. 实例化一个xhr对象*/const xhr = new XMLHttpRequest()/*判断是否有传参,有传参拼接在URL后面*/url = params ? url + function () {const keys = Object.keys(params)const values = Object.values(params)return '?' + keys.map((item, index) => item + '=' + values[index]).join('&')}() : url// console.log(url)xhr.open(method, url)// 有请求体,给请求头设置请求体文本类型xhr.setRequestHeader('Content-Type', 'application/json')/* 添加load事件,获取响应结果 */xhr.addEventListener('loadend', function () {/*200-300之间的状态码为响应成功状态码*/if (xhr.status >= 200 && xhr.status < 300) {/*返回的内容类型为JSON字符串,对它进行解析并返回*/resolve(JSON.parse(xhr.response))} else {reject(new Error(xhr.response))}})/*判断是否为post请求*/data ? xhr.send(JSON.stringify(data)) : xhr.send()})
}/*get请求 传参*/
/*new MyAxios({method: 'get',url: 'http://hmajax.itheima.net/api/area',params: {pname: '河北省',cname: '石家庄市'}
}).then(result => {console.log(result)
}).catch(error => {console.log(error)
})*//*post请求*/
/*new MyAxios({method: 'post',url: 'http://hmajax.itheima.net/api/register',data: {username: 'itheima095', password:' 123456'}
}).then(result => {console.log(result)
}).catch(error => {console.log(error)
})*//*获取城市天气*/
/*new MyAxios({method: 'get',url: 'http://hmajax.itheima.net/api/weather',params: {city: '110100'}
}).then(result => {console.log(result)
}).catch(error => {console.log(error)
})*//*获取天气案例*/
document.querySelector('.search-city').addEventListener('input', debounce(fun, 500))
const ul = document.querySelector(`ul`)
function fun(e) {console.log('发送请求', e.target.value)new MyAxios({url: 'http://hmajax.itheima.net/api/weather/city',params: {city: e.target.value}}).then(result => {console.log(result)ul.innerHTML = result.data.map(item => `<li data-code="${item.code}">${item.name}</li>`).join('')}).catch(error => {console.log(error)})
}
ul.addEventListener('click', function (e) {const li = e.targetif (li.tagName === 'LI') {console.log(li.dataset.code);new MyAxios({method: 'get',url: 'http://hmajax.itheima.net/api/weather',params: {city: li.dataset.code}}).then(result => {console.log(result)}).catch(error => {console.log(error)})}
})
//防抖函数
function debounce(fun, delay = 500) {let timer = nullreturn function (e) {if (timer)clearTimeout(timer)timer = setTimeout(function () {fun(e)timer = null}, delay)}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/99599.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

百度自研高性能ANN检索引擎,开源了

作者 | Puck项目组 导读 Puck是百度自研的开源ANN检索引擎。Puck开源项目包含两种百度自研的检索算法&#xff0c;以高召回、高准确、高吞吐为目标&#xff0c;适用于多种数据规模和场景。随着业务发展不断的优化和迭代&#xff0c;进行充分的技术开发和测试&#xff0c;确保了…

GEE/PIE遥感大数据处理与典型案例丨数据整合Reduce、云端数据可视化、数据导入导出及资产管理、机器学习算法等

随着航空、航天、近地空间等多个遥感平台的不断发展&#xff0c;近年来遥感技术突飞猛进。由此&#xff0c;遥感数据的空间、时间、光谱分辨率不断提高&#xff0c;数据量也大幅增长&#xff0c;使其越来越具有大数据特征。对于相关研究而言&#xff0c;遥感大数据的出现为其提…

文章预览 安防监控/视频存储/视频汇聚平台EasyCVR播放优化小tips

视频云存储/安防监控EasyCVR视频汇聚平台基于云边端智能协同&#xff0c;可实现视频监控直播、视频轮播、视频录像、云存储、回放与检索、智能告警、服务器集群、语音对讲、云台控制、电子地图、H.265自动转码H.264、平台级联等。为了便于用户二次开发、调用与集成&#xff0c;…

shell脚本介绍

当你进入Linux世界的大门时&#xff0c;就会遇到一个强大而又神奇的工具——Shell。Shell是一种命令行解释器&#xff0c;为你在Linux系统中与计算机进行互动提供了无限的可能性。 学习Shell可以让你获得强大的自动化和脚本编程能力&#xff0c;让你更高效地处理文件和目录、管…

ChatGPT可以生成Windows密钥

ChatGPT 可以回答许多问题、生成和修改代码&#xff0c;最近还可以生成 Windows 10 和 Windows 11 的许可证密钥。自从 OpenAI 的 ChatGPT 推出以来&#xff0c;人工智能已成为许多用户面临的挑战。 他们不断地试图削弱这种智力&#xff0c;或者想尝试它的局限性和可能性。例如…

elementUI可拖拉宽度抽屉

1&#xff0c;需求&#xff1a; 在elementUI的抽屉基础上&#xff0c;添加可拖动侧边栏宽度的功能&#xff0c;实现效果如下&#xff1a; 2&#xff0c;在原组件上添加自定义命令 <el-drawer v-drawerDrag"left" :visible.sync"drawerVisible" direc…

react使用hook封装一个search+input+checkbox组件

目录 react使用hook封装一个searchinputcheckbox组件searchPro.jsx使用组件效果 react使用hook封装一个searchinputcheckbox组件 searchPro.jsx import { Checkbox, Input } from "antd"; import React, { useEffect, useState } from "react"; import S…

LSTM基础

LSTM 视频讲得非常好 https://www.bilibili.com/video/BV1644y1W7sD/?spm_id_from333.788&vd_source3b42b36e44d271f58e90f86679d77db7门的概念 过去&#xff0c;不过去&#xff0c;过去一部分 点乘&#xff0c;0 concatenation&#xff0c;pointwise LSTM RNN 上一…

Docker 网络模式

文章目录 一、Docker 网络实现原理1.容器的端口映射 二、Docker的网络模式1.Host模式2.Container模式3.none模式4.bridge模式 三、自定义网络1、查看网络模式列表2、查看容器信息(包含配置、环境、网关、挂载、cmd等等信息&#xff09;3、指定分配容器IP地址 面试题 一、Docker…

Rasa 多轮对话机器人

Rasa 开源机器人 目录 Rasa 开源机器人 1. 学习资料 2. Rasa 安装 2.1. rasa 简介 2.2. Rasa系统结构 ​编辑 2.3. 项目的基本流程 ​编辑 2.4. Rasa安装 2.5. 组件介绍 3. Rasa NLU 3.0. NLU 推理输出格式 3.1. 训练数据 ./data/nlu.yml 数据文件 3.2. ./confi…

VB6.0 设置窗体的默认焦点位置在 TextBox 中

文章目录 VB6.0 窗体的加载过程确定指针的焦点位置添加代码效果如下未设置指定焦点已设置焦点 VB6.0 窗体的加载过程 在VB6.0中&#xff0c;窗体&#xff08;Form&#xff09;加载时会触发多个事件&#xff0c;这些事件按照特定的顺序执行。下面是窗体加载过程中常见事件的执行…

git co 命令是什么意思,用法是怎么样的

偶然看到同事使用 git co feat/xxx 来操作 git&#xff0c;以为 co 是什么 git 新命令&#xff0c;看起来很牛逼&#xff0c;所以问了下 chatgpt&#xff0c;chatgpt 的回答如下&#xff1a; git co 是 git checkout 的缩写形式&#xff0c;需要在Git的全局配置或别名配置中启用…