一.定义
AJAX是异步的 JavaScript和XML(Asynchronous JavaScript And XML)。简单点说,就是使用XMLHttpReguest 对象与服务器通信。它可以使用 JSON,XML,HTML和text 文本等格式发送和接收数据。AJAX 最吸引人的就是它的“异步”特性,也就是说它可以在不重新剧新页面的情况下与服务器通信,交换数据,或更新页面。
二.使用方法
1.axios库,与服务器进行数据通信
语法:1.引入axios.js:
https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js
2.使用axios函数(传入配置对象)!!!
axios({
url:'目标资源地址'
}).then((result)=>{
//对服务器返回的数据做后续处理
})
案例:
目标资源:
http://hmajax.itheima.net/api/province
代码:
<!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>
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>
三.认识URL
定义:统一资源定位符(英语:Uniform Resource Locator,缩写:URL,或称统一资源定位器、定位地址、URL地址)俗称网页地址,简称网址,是因特网上标准的资源的地址(Address),如同在网络上的门牌。它最初是由蒂姆·伯纳斯-李发明用来作为万维网的地址,现在它已经被万维网联盟编制为因特网标准RFC 1738。
例如:
https://www.baidu.com/index.html ——>网页资源
https://www.itheima.com/images/logo.png ——>图片资源
http://hmajax.itheima.net/api/province ——>数据资源
......
概念:URL就是统一资源定位符,简称网址,用于访问网站上的资源
组成:协议://域名/资源路径
axios({
url:'http://hmajax.itheima.net/api/province',
}).then(result=>{
}
四.URL查询参数
定义:浏览器提供给服务器哦的额外信息,让服务器返回浏览器想要的数据。
语法:http://xxxx.com/xxxx/xxxx?参数名1=值1 &参数名2 = 值2
axios查询参数语法:使用axios提供的params的选项
注意:axios 在运行时把参数名和值,会拼接到 url?参数名=值
城市列表:http://hmajax,itheima.net/api/city?pname=河北省
<!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>
<p class="my-p"></p>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
axios({
url:'http://hmajax.itheima.net/api/city',
params:{
pname:'河北省'
},
}).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>
五.中间案例——地区查询
<!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>
六.常见的请求方法
请求方法:对服务器资源,要执行的操作
axios请求配置:
url:请求的网址
method:请求的方法,GET可以忽略(不区分大小写)
data:提交的数据
案例:
通过 axios 提交用户名和密码,完成注册功能
注册用户 URL 地址:http://hmajax.itheima.net/api/register
请求方法:POST
参数名:
username 用户名(中英文和数字组成,最少8位)
password 密码(最少6位)
<!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>
</head>
<body>
<button class="btn">注册用户</button>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
/*
注册用户:http://hmajax.itheima.net/api/register
请求方法:POST
参数名:
username:用户名(中英文和数字组成,最少8位)
password:密码 (最少6位)
目标:点击按钮,通过axios提交用户和密码,完成注册
*/
document.querySelector('.btn').addEventListener('click', () => {
axios({
url:'http://hmajax.itheima.net/api/register',
method:'POST',
data:{
username:'huopengzhao123',
password:'123456'
}
}).then(result=>{
console.log(result)
}
)
})
</script>
</body>
</html>
七.axios错误处理
语法:在then方法的后面,通过语法调用catch方法,传入回调函数并定义形参
案例:注册时,重复注册时通过弹框提醒用户错误原因
<!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>
</head>
<body>
<button class="btn">注册用户</button>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
document.querySelector('.btn').addEventListener('click', () => {
axios({
url:'http://hmajax.itheima.net/api/register',
method:'POST',
data:{
username:'huopengzhao123',
password:'123456'
}
}).then(result=>{
console.log(result)
}
).catch(error=>{
console.log(error)
console.log(error.response.data.message)
alert(error.response.data.message)
})
})
</script>
</body>
</html>
八.http协议-请求报文
HTTP协议:规定了浏览器发送以及服务器返回内容的样式
请求报文:浏览器按照http协议要求的格式,发送给服务器的内容
格式:
- 请求行:请求方法,URL,协议
- 请求头:以键值对的格式携带的附加信息,比如:Content-Type
- 空行:分隔请求头,空行之后的是发送给服务器的资源
- 请求体:发送的资源
九.请求报文——错误排查
需求:通过请求报文排查错误原因,并修复正确的用户名和密码无法登录
- 用户名:huopengzhao123
- 密码:123456
//可找出下面代码的错误的地方
<!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">
JS中会动态插入提示文字
</div>
<!-- 表单 -->
<div class="form_wrap">
<form>
<div class="mb-3">
<label for="username" class="form-label">账号名</label>
<input type="text" class="form-control username" name="username" aria-describedby="usernameHelp">
</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>
<script>
// 1.获取 alert
const alertCom = document.querySelector('.alert')
// 2.抽取提示框的方法
function showAlert(msg, classname) {
alertCom.innerText = msg
alertCom.classList.add(classname)
alertCom.classList.add('show')
setTimeout(() => {
// 延迟隐藏
alertCom.classList.remove('show')
alertCom.classList.remove(classname)
}, 2000);
}
// 3.给登录按钮绑定点击事件,提交输入的用户信息到服务器
document.querySelector('.btn-login').addEventListener('click', function () {
// 3.1 获取输入的用户名和密码
const username = document.querySelector('.username').value
const password = document.querySelector('.username').value
//错误的地方
// 3.2用户名 密码 长度判断
if (username.trim().length < 8) {
showAlert('用户名长度需要大于等于8', 'alert-danger')
return
}
if (password.trim().length < 6) {
showAlert('密码长度需要大于等于6', 'alert-danger')
return
}
// 3.3 通过axios提交到服务器 并 提示用户 成功 / 失败
axios({
url: 'http://hmajax.itheima.net/api/login',
method: 'post',
data: {
username,
password
}
}).then(res => {
// 显示提示框
showAlert(res.data.message, 'alert-success')
}).catch(err => {
// 显示警示框
showAlert(err.response.data.message, 'alert-danger')
})
})
</script>
</body>
</html>
十.HTTP——响应报文
HTTP 协议:规定了浏览器发送及服务器返回内容的格式响应报文:服务器按照 HTTP 协议要求的格式,返回给浏览器的内容
响应报文:服务器按照 HTTP 协议要求的格式,返回给浏览器的内容
- 响应行(状态行):协议、HTTP 响应状态码、状态信息
- 响应头:以键值对的格式携带的附加信息,比如:Content-Type
- 空行:分隔响应头,空行之后的是服务器返回的资源
- 响应体:返回的资源
http响应状态码
用来表明请求是否成果
十一.接口文档
接口文档:描述接口的文章
接口:使用AJAX和服务器通讯时,使用的URL,请求方法,以及参数
资料:获取-省份列表 - AJAX阶段(黑马)
案例(登陆):
<!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>
</head>
<body>
<button class="btn">用户登录</button>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
// 用户注册
// axios({
// url: 'http://hmajax.itheima.net/api/register',
// method: 'post',
// data: {
// username: 'itheima007',
// password: '7654321'
// }
// })
document.querySelector('.btn').addEventListener('click', () => {
// 用户登录
axios({
url: 'http://hmajax.itheima.net/api/login',
method: 'post',
data: {
username: 'itheima007',
password: '7654321'
}
})
})
</script>
</body>
</html>
十二.form-serialize插件
作用:快速收集表单元素
语法:
const form = document.querySelector('.example-form')
const data = serialize(for, {hash: true. empty: true})
<!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>13.form-serialize插件使用</title>
</head>
<body>
<form action="javascript:;" class="example-form">
<input type="text" name="uname">
<br>
<input type="text" name="pwd">
<br>
<input type="button" class="btn" value="提交">
</form>
<!--
目标:在点击提交时,使用form-serialize插件,快速收集表单元素值
-->
<script src="./js/form-serialize.js"></script>
<script>
document.querySelector('.btn').addEventListener('click', () => {
const form = document.querySelector('.example-form')
const data =serialize(form, {hash: true, empty: true})
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>
<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 获取提示框
//2.2封装提示框的函数
const myAlert = document.querySelector('.alert')
function alertFn(msg, isSuccess) {
myAlert.classList.add('show')
myAlert.innerHTML= msg
const bgColor = isSuccess ? 'alert-success' : 'alert-danger'
myAlert.classList.add(bgColor)
setTimeout(() => {
myAlert.classList.remove('show')
myAlert.classList.remove(bgColor)
},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>