当前位置: 首页 > news >正文

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)}
}

相关文章:

Ajax + Promise复习简单小结simple

axios使用 先看看老朋友 axios axios是基于Ajaxpromise封装的 看一下他的简单使用 安装&#xff1a;npm install axios --save 引入&#xff1a;import axios from axios GitHub地址 基本使用 axios({url: http://hmajax.itheima.net/api/province}).then(function (result…...

WebDAV之π-Disk派盘 + 小书匠

小书匠是一款功能丰富,强大的知识管理工具。全平台覆盖,离线数据存储,自定义数据服务器,所见即所得的 markdown 编辑体验。 小书匠提供了多种实用的编辑模式,例如:栏编辑、双栏编辑、三栏编辑、全屏写作、全屏阅读等。并且该软件还提供了许多有用的扩展语法,比如Latex公…...

LTE ATTACH流程、PDN流程、PGW地址分配介绍

1、S-GW\P-GW选择 MME根据S-GW和P-GW的拓扑信息进行S-GW/P-GW的选择&#xff0c;在S-GW的候选序列和P-GW的候选序列中比较&#xff0c;寻找是否有合一的S-GW/P-GW&#xff0c;并且根据S-GW的优先级和权重信息进行排序&#xff0c;得到S-GW/P-GW的候选组。 2、SGW>PGW连接 PD…...

SQL sever中用户管理

目录 一、用户管理常见方法 二、用户管理方法示例 2.1. 创建登录账户&#xff1a; 2.1.1 检查是否创建账户成功&#xff1a; 2.2. 创建数据库用户&#xff1a; 2.2.1检查用户是否创建成功&#xff1a; 2.3. 授予权限&#xff1a; 2.3.1授予 SELECT、INSERT 和 U…...

linux————pxe网络批量装机

目录 一、概述 什么是pxe pxe组件 二、搭建交互式pxe装机 一、配置基础环境 二、配置vsftpd 三、配置tftp 四、准备pxelinx.0文件、引导文件、内核文件 一、准备pxelinux.0 二、准备引导文件、内核文件 五、配置dhcp 一、安装dhcp 二、配置dhcp 六、创建default文…...

处理时延降低24倍,联通云粒数据引擎优化实践

*作者&#xff1a;郑扬勇&#xff0c;云粒星河数据中台产品负责人 云粒智慧科技有限公司成立于 2018 年 6 月&#xff0c;是中国联通集团混改以来成立的首家合资公司&#xff0c;是中国智慧城市数智化建设者。一直以来&#xff0c;云粒智慧以数字化、智能化、集约化产品为核心&…...

学习MATLAB

今日&#xff0c;在大学慕课上找了一门关于MATLAB学习的网课&#xff0c;MATLAB对于我们这种自动化的学生应该是很重要的&#xff0c;之前也是在大三的寒假做自控的课程设计时候用到过&#xff0c;画一些奈奎斯特图&#xff0c;根轨迹图以及伯德图&#xff0c;但那之后也就没怎…...

React 18 对 state 进行保留和重置

参考文章 对 state 进行保留和重置 各个组件的 state 是各自独立的。根据组件在 UI 树中的位置&#xff0c;React 可以跟踪哪些 state 属于哪个组件。可以控制在重新渲染过程中何时对 state 进行保留和重置。 UI 树 浏览器使用许多树形结构来为 UI 建立模型。DOM 用于表示 …...

MySQL之事务与引擎

目录 一、事物 1、事务的概念 2、事务的ACID特点 3、事务之间的相互影响 4、Mysql及事务隔离级别(四种) 1、查询会话事务隔离级别 2、查询会话事务隔离级别 3、设置全局事务隔离级别 4、设置会话事务隔离级别 5、事务控制语句 6、演示 1、测试提交事务 2、测试事务回滚 4…...

Flink集群常见的监控指标

为确保能够全面、实时地监控Flink集群的运行状态和性能指标。以下是监控方案的主要组成部分&#xff1a; Flink集群概览&#xff1a;通过访问Flink的JobManager页面&#xff0c;您可以获取集群的总体信息&#xff0c;包括TaskManager的数量、任务槽位数量、运行中的作业以及已…...

React常见知识点

1. setCount(10)与setCount(preCount > preCount 10) 的区别&#xff1a; import React, { useState } from react; export default function CounterHook() {const [count, setCount] useState(() > 10);console.log(CounterHook渲染);function handleBtnClick() {//…...

Vue-router路由

配置路由 相当于SpringMVC的Controller 路径然后&#xff0c;跳转到对应的组件 一键生成前端项目文档...

JVM-CMS

when 堆大小要求为4-8G 原理 初始标记&#xff1a;执行CMS线程->STW&#xff0c;标记GC Root直接关联的对象->低延迟 并发标记&#xff1a;执行CMS线程和业务线程&#xff0c;从GC Root直接关联的对象开始遍历整个对象图 重新标记&#xff1a;执行CMS线程->STW&a…...

无涯教程-Flutter - Dart简介

Dart是一种开源通用编程语言&#xff0c;它最初是由Google开发的&#xff0c; Dart是一种具有C样式语法的面向对象的语言&#xff0c;它支持诸如接口&#xff0c;类之类的编程概念&#xff0c;与其他编程语言不同&#xff0c;Dart不支持数组&#xff0c; Dart集合可用于复制数据…...

如何创建美观的邮件模板并通过qq邮箱的SMTP服务向用户发送

最近在写注册功能的自动发送邮箱告知验证码的功能&#xff0c;无奈根本没有学过前端&#xff0c;只有写Qt的qss基础&#xff0c;只好借助网页设计自己想要的邮箱格式&#xff0c;最终效果如下: 也推销一下自己的项目ShaderLab&#xff0c;可运行ShaderToy上的大部分着色器代码&…...

手机无人直播软件在苹果iOS系统中能使用吗?

在现代社交媒体的时代&#xff0c;直播带货已经成为了一种热门的销售途径。通过直播&#xff0c;人们可以远程分享自己的商品&#xff0c;与观众进行互动&#xff0c;增强沟通和参与感。而如今&#xff0c;手机无人直播软件更是成为了直播带货领域的一项火爆的技术。那么&#…...

创建2个线程并执行(STL/Windows/Linux)

C并发编程入门 目录 STL 写法 #include <thread> #include <iostream> using namespace std;void thread_fun1(void) {cout << "one STL thread 1!" << endl; }void thread_fun2(void) {cout << "one STL thread 2!" <…...

Redis可以干什么

Redis可以做什么&#xff1f; 缓存 Redis作为一款高性能的缓存数据库&#xff0c;能够将常用的数据存储在内存中&#xff0c;以提高读写效率。它支持多种数据结构&#xff0c;如字符串、哈希表、列表、集合等&#xff0c;让你可以根据业务需求选择合适的数据结构进行缓存。 …...

R语言+Meta分析;论文新方向

Meta分析是针对某一科研问题&#xff0c;根据明确的搜索策略、选择筛选文献标准、采用严格的评价方法&#xff0c;对来源不同的研究成果进行收集、合并及定量统计分析的方法&#xff0c;最早出现于“循证医学”&#xff0c;现已广泛应用于农林生态&#xff0c;资源环境等方面。…...

实战系列(二)| MybatisPlus详细介绍,包含代码详解

目录 1. MybatisPlus 的基本功能2. 基本用法3. MybatisPlus 的配置4. MybatisPlus 的实体类、Mapper 接口、Service 类和 Controller 类 MybatisPlus 是一个功能强大的 MyBatis 增强工具&#xff0c;它提供了丰富的特性来简化操作数据库的代码。它主要用于简化 JDBC 操作&#…...

横向对比 npm、pnpm、tnpm、yarn 优缺点

前端工程化是现代Web开发中不可或缺的一环&#xff0c;它的出现极大地提升了前端开发的效率和质量。 在过去&#xff0c;前端开发依赖于手动管理文件和依赖&#xff0c;这导致了许多问题&#xff0c;如版本冲突、依赖混乱和构建繁琐等。而今&#xff0c;随着众多前端工程化工具…...

安防监控/视频汇聚/云存储/AI智能视频融合平台页面新增地图展示功能

AI智能分析网关包含有20多种算法&#xff0c;包括人脸、人体、车辆、车牌、行为分析、烟火、入侵、聚集、安全帽、反光衣等等&#xff0c;可应用在安全生产、通用园区、智慧食安、智慧城管、智慧煤矿等场景中。将网关硬件结合我们的视频汇聚/安防监控/视频融合平台EasyCVR一起使…...

机器人中的数值优化(九)——拟牛顿方法(下)、BB方法

本系列文章主要是我在学习《数值优化》过程中的一些笔记和相关思考&#xff0c;主要的学习资料是深蓝学院的课程《机器人中的数值优化》和高立编著的《数值最优化方法》等&#xff0c;本系列文章篇数较多&#xff0c;不定期更新&#xff0c;上半部分介绍无约束优化&#xff0c;…...

java 从resource下载excel打不开

GetMapping("/download/template")public void template(HttpServletResponse response) throws IOException {ServletOutputStream outputStream response.getOutputStream();InputStream inputStream null;try {//从resource获取excel文件流inputStream getClas…...

NS2安装及入门实例——(ns2.35 / Ubuntu20.04)

文章目录 一、ns2安装1、更新系统源2、准备工作3、下载安装包4、安装5、问题① 问题1② 问题2③ 问题3 6、安装成功7、环境配置 二、nam安装1、安装2、问题 三、实例 一、ns2安装 1、更新系统源 sudo apt-get update sudo apt-get upgrade2、准备工作 sudo apt-get install …...

平面设计的三大基本元素 优漫动游

平面设计需要美术基础&#xff0c;有美术基础的新人往往能更快完成平面设计岗的转行&#xff0c;在专业培训机构内讲师授课时也会从平面设计的基础——三大基本元素开始。今天就跟大家具体介绍一下平面设计的三大基本元素&#xff0c;让大家知道到底都有哪些。 平面设计的三…...

【电子取证篇】汽车取证检验标准

【电子取证篇】汽车取证检验标准 汽车取证鉴定可能涉及的测试/测量方法—【蘇小沐】 GA/T 976-2012《电子数据法庭科学鉴定通用方法》&#xff1b; GA/T 1998-2022《汽车车载电子数据提取技术规范》&#xff1b; GA/T 1999.2-2022《道路交通事故车辆速度鉴定方法 第2部分&…...

【元宇宙】游戏应用商城对元宇宙的影响

游戏行业不仅是创意设计原则的信息源&#xff0c;还是构建“下一代互联网”的基础技术。它也是元宇宙的经济活动先例。 究竟为什么会认为应用商城设置的30%佣金将导致元宇宙“无法实现”呢&#xff1f;有三个核心原因。首先&#xff0c;应用商城阻止了企业对元宇宙的投资&…...

win10-docker-mysql镜像安装运行基础

win10-docker-mysql镜像安装运行基础 文章目录 win10-docker-mysql镜像安装运行基础一、搜索可用镜像1.1 查询mysql镜像1.2 确定镜像版本号 二、运行mysql容器2.1 进入mysql2.2 测试mysql是否正常 三、将mysql数据存储目录映射到宿主机做持久化 一、搜索可用镜像 1.1 查询mysq…...

VirtualBox7+Ubuntu22集群规划

1. 目的: 新入手了一台小主机&#xff08;8核 / Intel(R) Xeon(R) W-10885M CPU 2.40GHz 2.40 GHz, 16vCpu / 64G RAM / 系统类型 64 位操作系统, 基于 x64 的处理器&#xff09;&#xff0c;原装了一套Win11专业版&#xff0c;打算用VirtualBox 虚拟一个集群。 2. …...

wordpress基本教程/微商软文范例大全100

Java Number内置数据类型&#xff1a;byte int long short double 等int i 10&#xff1b;float i 10.5f;实际开发中&#xff0c;经常遇到使用对象&#xff0c;而不是内置数据类型,包装类(Integer Long Double Float Short)都是抽象类 Number的子类内置数据类型被当作对象使用…...

文案素材网站/网络营销策略理论有哪些

XP系统提示“HTTP500内部服务器错误”怎么办&#xff1f;这是近来不少使用windowsxp系统的朋友们都遇到的问题。为了帮助大家更好地使用xp系统&#xff0c;下面小编就分享HTTP500内部服务器错误问题的原因和解决方法。一、造成500错误常见原因有&#xff1a;ASP语法出错、ACCES…...

wordpress 显示全文/北京官网seo收费

1、在黄金期内一定会面临很多压力&#xff0c;但千万不要让自己在&#xff02;焦虑&#xff02;状态下沉浸很久&#xff0c;因为焦虑会取代你的能力。相信坚持走下去的过程中会有答案。 2、正确地审视自己的能力。中国的特殊现状造就了一大批年轻的高管&#xff0c;机会够好&am…...

数据库里建设好的网站为什么外网进不去网站/建立一个企业网站需要多少钱

我是selenium的新手,我正在尝试使用Selenium IDE(2.9.0)创建一个基本的第一个单击和记录脚本,然后我使用Selenium WebDriver(2.48.0)进行优化.我录制了一个工作脚本(参见本问题末尾的附件),并将其导出为“python 2 / unittest / WebDriver”.但是,源代码清楚地表明它存在一些问…...

动画设计就业前景/seo快速排名源码

http://www.docin.com/p-443803801.html...

网站建设的流程分析/百度指数代表什么意思

1、下载putty https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html2、安装和配置puttya、host name 192.168.0.222b、saved sessions Linux c、saved、open3、putty设置公钥和私钥a、点击开始菜单找到putty目录&#xff0c;点击puttygenb、点击Generate生成密钥&a…...