一、AJAX
1.AJAX概念
使浏览器的XMLHttpRequest对象与服务器通信
浏览器网页中,使用 AJAX技术(XHR对象)发起获取省份列表数据的请求,服务器代码响应准备好的省份列表数据给前端,前端拿到数据数组以后,展示到网页
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX概念和axios使用</title>
</head>
<body>
<!--
axios库地址:https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js
省份数据地址:http://hmajax.itheima.net/api/province
目标: 使用axios库, 获取省份列表数据, 展示到页面上
1. 引入axios库
-->
<p class="my-p"></p>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
// 2. 使用axios函数
axios({
url: 'http://hmajax.itheima.net/api/province'
}).then(result => {
console.log(result)
// 好习惯:多打印,确认属性名
console.log(result.data.list)
console.log(result.data.list.join('<br>'))
// 把准备好省份列表,插入到页面
document.querySelector('.my-p').innerHTML = result.data.list.join('<br>')
})
</script>
</body>
</html>
2.URL
概念:URL即统一资源定位符,简称网址,用于定位网络中的资源(资源指的是:网页、图片、数据、视频、音频等等)
组成:协议、域名、资源路径
http协议:超文本传输协议,规定了浏览器和服务器传递数据的格式
域名:标记服务器在互联网当中的方位,网络中有很多服务器,你想访问哪一台,就需要知道它的域名才可以
资源路径:一个服务器内有多个资源,用于标识你要访问的资源具体的位置
3.查询参数
什么是查询参数 ?
-
携带给服务器额外信息,获得对应数据(让服务器返回我想要的某一部分数据而不是全部数据)
-
举例:查询河北省下属的城市列表,需要先把河北省传递给服务器
查询参数语法:
-
在 url 网址后面用?拼接格式:XXXX?参数名1=值1&参数名2=值2
-
参数名一般是后端规定的,值前端看情况传递即可
axios如何携带查询参数:
通过params选项
axios({
url: '目标资源地址',
params: {
参数名: 值
}
}).then(result => {
// 对服务器返回的数据做后续处理
})
4.案例-查询地区列表
巩固查询参数的使用,并查看多对查询参数如何传递
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>案例_地区查询</title>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
/>
<style>
:root {
font-size: 15px;
}
body {
padding-top: 15px;
}
</style>
</head>
<body>
<div class="container">
<form id="editForm" class="row">
<!-- 输入省份名字 -->
<div class="mb-3 col">
<label class="form-label">省份名字</label>
<input
type="text"
value="北京"
name="province"
class="form-control province"
placeholder="请输入省份名称"
/>
</div>
<!-- 输入城市名字 -->
<div class="mb-3 col">
<label class="form-label">城市名字</label>
<input
type="text"
value="北京市"
name="city"
class="form-control city"
placeholder="请输入城市名称"
/>
</div>
</form>
<button type="button" class="btn btn-primary sel-btn">查询</button>
<br /><br />
<p>地区列表:</p>
<ul class="list-group">
<!-- 示例地区 -->
<li class="list-group-item">东城区</li>
</ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
/*
获取地区列表: http://hmajax.itheima.net/api/area
查询参数:
pname: 省份或直辖市名字
cname: 城市名字
*/
// 目标: 根据省份和城市名字, 查询地区列表
// 1. 查询按钮-点击事件
document.querySelector(".sel-btn").addEventListener("click", () => {
// 2. 获取省份和城市名字
let pname = document.querySelector(".province").value;
let cname = document.querySelector(".city").value;
// 3. 基于axios请求地区列表数据
axios({
url: "http://hmajax.itheima.net/api/area",
params: {
pname,
cname,
},
}).then((result) => {
// console.log(result)
// 4. 把数据转li标签插入到页面上
let list = result.data.list;
console.log(list);
let theLi = list
.map((areaName) => `<li class="list-group-item">${areaName}</li>`)
.join("");
console.log(theLi);
document.querySelector(".list-group").innerHTML = theLi;
});
});
</script>
</body>
</html>
5.常用请求方法和数据提交
请求方法是一些固定单词的英文,例如:GET,POST,PUT,DELETE,PATCH(这些都是http协议规定的),每个单词对应一种对服务器资源要执行的操作
axios({
url: '目标资源地址',
method: '请求方法',
data: {
参数名: 值
}
}).then(result => {
// 对服务器返回的数据做后续处理
})
6.axios错误处理
如果注册相同的用户名,则会遇到注册失败的请求,也就是 axios 请求响应失败了,你会在控制台看到如图的错误:
axios({
// ...请求选项
}).then(result => {
// 处理成功数据
}).catch(error => {
// 处理失败错误
})
document.querySelector('.btn').addEventListener('click', () => {
axios({
url: 'http://hmajax.itheima.net/api/register',
method: 'post',
data: {
username: 'itheima007',
password: '7654321'
}
}).then(result => {
// 成功
console.log(result)
}).catch(error => {
// 失败
// 处理错误信息
console.log(error)
console.log(error.response.data.message)
alert(error.response.data.message)
})
})
7.HTTP协议-报文

8.案例-登陆
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>案例_登录</title>
<!-- 引入bootstrap.css -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
<!-- 公共 -->
<style>
html,
body {
background-color: #EDF0F5;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.container {
width: 520px;
height: 540px;
background-color: #fff;
padding: 60px;
box-sizing: border-box;
}
.container h3 {
font-weight: 900;
}
</style>
<!-- 表单容器和内容 -->
<style>
.form_wrap {
color: #8B929D !important;
}
.form-text {
color: #8B929D !important;
}
</style>
<!-- 提示框样式 -->
<style>
.alert {
transition: .5s;
opacity: 0;
}
.alert.show {
opacity: 1;
}
</style>
</head>
<body>
<div class="container">
<h3>欢迎-登录</h3>
<!-- 登录结果-提示框 -->
<div class="alert alert-success" role="alert">
提示消息
</div>
<!-- 表单 -->
<div class="form_wrap">
<form>
<div class="mb-3">
<label for="username" class="form-label">账号名</label>
<input type="text" class="form-control username">
</div>
<div class="mb-3">
<label for="password" class="form-label">密码</label>
<input type="password" class="form-control password">
</div>
<button type="button" class="btn btn-primary btn-login"> 登 录 </button>
</form>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
// 目标1:点击登录时,用户名和密码长度判断,并提交数据和服务器通信
// 1.1 登录-点击事件
document.querySelector('.btn-login').addEventListener('click', () => {
// 1.2 获取用户名和密码
const username = document.querySelector('.username').value
const password = document.querySelector('.password').value
// console.log(username, password)
// 1.3 判断长度
if (username.length < 8) {
console.log('用户名必须大于等于8位')
return // 阻止代码继续执行
}
if (password.length < 6) {
console.log('密码必须大于等于6位')
return // 阻止代码继续执行
}
// 1.4 基于axios提交用户名和密码
// console.log('提交数据到服务器')
axios({
url: 'http://hmajax.itheima.net/api/login',
method: 'POST',
data: {
username,
password
}
}).then(result => {
console.log(result)
console.log(result.data.message)
}).catch(error => {
console.log(error)
console.log(error.response.data.message)
})
})
</script>
</body>
</html>
9.案例-登陆-提示信息
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>案例_登录_提示消息</title>
<!-- 引入bootstrap.css -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
<!-- 公共 -->
<style>
html,
body {
background-color: #EDF0F5;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.container {
width: 520px;
height: 540px;
background-color: #fff;
padding: 60px;
box-sizing: border-box;
}
.container h3 {
font-weight: 900;
}
</style>
<!-- 表单容器和内容 -->
<style>
.form_wrap {
color: #8B929D !important;
}
.form-text {
color: #8B929D !important;
}
</style>
<!-- 提示框样式 -->
<style>
.alert {
transition: .5s;
opacity: 0;
}
.alert.show {
opacity: 1;
}
</style>
</head>
<body>
<div class="container">
<h3>欢迎-登录</h3>
<!-- 登录结果-提示框 -->
<div class="alert alert-success" role="alert">
提示消息
</div>
<!-- 表单 -->
<div class="form_wrap">
<form>
<div class="mb-3">
<label for="username" class="form-label">账号名</label>
<input type="text" class="form-control username">
</div>
<div class="mb-3">
<label for="password" class="form-label">密码</label>
<input type="password" class="form-control password">
</div>
<button type="button" class="btn btn-primary btn-login"> 登 录 </button>
</form>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
// 目标1:点击登录时,用户名和密码长度判断,并提交数据和服务器通信
// 目标2:使用提示框,反馈提示消息
// 2.1 获取提示框
const myAlert = document.querySelector('.alert')
/**
* 2.2 封装提示框函数,重复调用,满足提示需求
* 功能:
* 1. 显示提示框
* 2. 不同提示文字msg,和成功绿色失败红色isSuccess(true成功,false失败)
* 3. 过2秒后,让提示框自动消失
*/
function alertFn(msg, isSuccess) {
// 1> 显示提示框
myAlert.classList.add('show')
// 2> 实现细节
myAlert.innerText = msg
const bgStyle = isSuccess ? 'alert-success' : 'alert-danger'
myAlert.classList.add(bgStyle)
// 3> 过2秒隐藏
setTimeout(() => {
myAlert.classList.remove('show')
// 提示:避免类名冲突,重置背景色
myAlert.classList.remove(bgStyle)
}, 2000)
}
// 1.1 登录-点击事件
document.querySelector('.btn-login').addEventListener('click', () => {
// 1.2 获取用户名和密码
const username = document.querySelector('.username').value
const password = document.querySelector('.password').value
// console.log(username, password)
// 1.3 判断长度
if (username.length < 8) {
alertFn('用户名必须大于等于8位', false)
console.log('用户名必须大于等于8位')
return // 阻止代码继续执行
}
if (password.length < 6) {
alertFn('密码必须大于等于6位', false)
console.log('密码必须大于等于6位')
return // 阻止代码继续执行
}
// 1.4 基于axios提交用户名和密码
// console.log('提交数据到服务器')
axios({
url: 'http://hmajax.itheima.net/api/login',
method: 'POST',
data: {
username,
password
}
}).then(result => {
alertFn(result.data.message, true)
console.log(result)
console.log(result.data.message)
}).catch(error => {
alertFn(error.response.data.message, false)
console.log(error)
console.log(error.response.data.message)
})
})
</script>
</body>
</html>
9.form-serialize插件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>form-serialize插件使用</title>
</head>
<body>
<form action="javascript:;" class="example-form">
<input type="text" name="username">
<br>
<input type="text" name="password">
<br>
<input type="button" class="btn" value="提交">
</form>
<!--
目标:在点击提交时,使用form-serialize插件,快速收集表单元素值
1. 把插件引入到自己网页中
-->
<script src="./lib/form-serialize.js"></script>
<script>
document.querySelector('.btn').addEventListener('click', () => {
/**
* 2. 使用serialize函数,快速收集表单元素的值
* 参数1:要获取哪个表单的数据
* 表单元素设置name属性,值会作为对象的属性名
* 建议name属性的值,最好和接口文档参数名一致
* 参数2:配置对象
* hash 设置获取数据结构
* - true:JS对象(推荐)一般请求体里提交给服务器
* - false: 查询字符串
* empty 设置是否获取空值
* - true: 获取空值(推荐)数据结构和标签结构一致
* - false:不获取空值
*/
const form = document.querySelector('.example-form')
const data = serialize(form, { hash: true, empty: true })
// const data = serialize(form, { hash: false, empty: true })
// const data = serialize(form, { hash: true, empty: false })
console.log(data)
})
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>案例_登录_插件使用</title>
<!-- 引入bootstrap.css -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
<!-- 公共 -->
<style>
html,
body {
background-color: #EDF0F5;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.container {
width: 520px;
height: 540px;
background-color: #fff;
padding: 60px;
box-sizing: border-box;
}
.container h3 {
font-weight: 900;
}
</style>
<!-- 表单容器和内容 -->
<style>
.form_wrap {
color: #8B929D !important;
}
.form-text {
color: #8B929D !important;
}
</style>
<!-- 提示框样式 -->
<style>
.alert {
transition: .5s;
opacity: 0;
}
.alert.show {
opacity: 1;
}
</style>
</head>
<body>
<div class="container">
<h3>欢迎-登录</h3>
<!-- 登录结果-提示框 -->
<div class="alert alert-success" role="alert">
提示消息
</div>
<!-- 表单 -->
<div class="form_wrap">
<form class="login-form">
<div class="mb-3">
<label for="username" class="form-label">账号名</label>
<input type="text" class="form-control username" name="username">
</div>
<div class="mb-3">
<label for="password" class="form-label">密码</label>
<input type="password" class="form-control password" name="password">
</div>
<button type="button" class="btn btn-primary btn-login"> 登 录 </button>
</form>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<!-- 3.1 引入插件 -->
<script src="./lib/form-serialize.js"></script>
<script>
// 目标1:点击登录时,用户名和密码长度判断,并提交数据和服务器通信
// 目标2:使用提示框,反馈提示消息
// 目标3:使用form-serialize插件,收集用户名和密码
// 2.1 获取提示框
const myAlert = document.querySelector('.alert')
/**2.2 封装提示框函数,重复调用,满足提示需求
* 功能:
* 1. 显示提示框
* 2. 不同提示文字msg,和成功绿色失败红色isSuccess(true成功,false失败)
* 3. 过2秒后,让提示框自动消失
*/
function alertFn(msg, isSuccess) {
// 1> 显示提示框
myAlert.classList.add('show')
// 2> 实现细节
myAlert.innerText = msg
const bgStyle = isSuccess ? 'alert-success' : 'alert-danger'
myAlert.classList.add(bgStyle)
// 3> 过2秒隐藏
setTimeout(() => {
myAlert.classList.remove('show')
// 提示:避免类名冲突,重置背景色
myAlert.classList.remove(bgStyle)
}, 2000)
}
// 1.1 登录-点击事件
document.querySelector('.btn-login').addEventListener('click', () => {
// 3.2 使用serialize函数,收集登录表单里用户名和密码
const form = document.querySelector('.login-form')
const data = serialize(form, { hash: true, empty: true })
console.log(data)
// {username: 'itheima007', password: '7654321'}
const { username, password } = data
// 1.2 获取用户名和密码
// const username = document.querySelector('.username').value
// const password = document.querySelector('.password').value
console.log(username, password)
// 1.3 判断长度
if (username.length < 8) {
alertFn('用户名必须大于等于8位', false)
console.log('用户名必须大于等于8位')
return // 阻止代码继续执行
}
if (password.length < 6) {
alertFn('密码必须大于等于6位', false)
console.log('密码必须大于等于6位')
return // 阻止代码继续执行
}
// 1.4 基于axios提交用户名和密码
// console.log('提交数据到服务器')
axios({
url: 'http://hmajax.itheima.net/api/login',
method: 'POST',
data: {
username,
password
}
}).then(result => {
alertFn(result.data.message, true)
console.log(result)
console.log(result.data.message)
}).catch(error => {
alertFn(error.response.data.message, false)
console.log(error)
console.log(error.response.data.message)
})
})
</script>
</body>
</html>
其实就是通过form-serialize可以直接获得是有表单元素,而不需要一一获取。