Ajax(Asynchronous Javascript And XML),即是异步的JavaScript和XML,Ajax其实就是浏览器与服务器之间的一种异步通信方式

异步的JavaScript,它可以异步地向服务器发送请求,在等待响应的过程中,不会阻塞当前页面,在这种情况下,浏览器可以做自己的事情。直到成功获取响应后,浏览器才开始处理响应数据。

所以简单来说,Ajax就是在浏览器不重新加载网页的情况下,对页面的某部分进行更新。

1.介绍

1.AJAX 的使用

在 js 中有内置的构造函数来创建 ajax 对象

创建 ajax 对象以后,我们就使⽤ ajax 对象的⽅法去发送请求和接受响应

Ajax的一个最大的特点是无需刷新页面便可向服务器传输或读写数据(又称无刷新更新页面),这一特点主要得益于XMLHTTP组件

XMLHTTPRequest对象

2.express

在学习Ajax中我们用到express框架,我们先引入express

1
npm init --yes
1
npm -i express

设置完成后我们引入express,并且创建express对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* 引入express */
const express = require('express');
/* 创建对象 */
const app = express();

/* 创建路由规则 */
/* 对请求报文的封装
对响应报文的封装 */
app.get("/serve",(request,response)=>{
/* 设置响应头 设置允许跨域访问 */
response.setHeader('Access-Control-Allow-Origin','*');
/* 设置响应体 */
response.send("Hello");
})

/* 监听端口启动服务 */
app.listen(8030,()=>{
console.log("服务启动");
})

3.Ajax

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const btn = document.querySelector("button");
const result = document.querySelector(".box");
btn.addEventListener("click",function(){
/* 创建对象 */
const xhr = new XMLHttpRequest()
/* 初始化 设置请求方法和url */
xhr.open('GET',"http://localhost:8030/serve");
/* 发送 */
xhr.send();
/* 事件绑定 */
xhr.addEventListener("readystatechange",function(){
if (xhr.readyState === 4)
{
if (xhr.status >= 200 && xhr.status < 300){
/* console.log(xhr.status);
console.log(xhr.statusText); */
result.innerHTML=xhr.response;
}else {

}
}
})

4.ajax 状态码 - xhr.readyState

ajax 状态码 - xhr.readyState

readyState === 0 : 表示未初始化完成,也就是 open 方法还没有执行

readyState === 1 : 表示配置信息已经完成,也就是执行完 open 之后

readyState === 2 : 表示 send 方法已经执行完成

readyState === 3 : 表示正在解析响应内容

readyState === 4 : 表示响应内容已经解析完毕,可以在客户端使用

在当===4时我们使用服务端给我们的数据

5.readyStateChange事件

这个事件是专⻔用来监听 ajax 对象的 readyState 值改变的的行为

也就是说只要 readyState 的值发生变化了,那么就会触发该事件

所以我们就在这个事件中来监听 ajax 的 readyState 是不是 4

6.GET设置请求参数

1
xhr.open('GET',"http://localhost:8030/serve?a=100&b=200");

7.AJAXPost请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const div =document.querySelector("div");

div.addEventListener("mousemove",function(){
const xhr = new XMLHttpRequest();
xhr.open('POST',"http://localhost:8030/serve");
xhr.send();

xhr.addEventListener("readystatechange",function(){
if (xhr.readyState === 4){
if (xhr.status >= 200 && xhr.status <300){
div.innerHTML=xhr.responseText;
}else{

}
}
})
})

在serve.js中给post

1
2
3
4
5
6
app.post("/serve",(request,response)=>{
/* 设置响应头 设置允许跨域访问 */
response.setHeader('Access-Control-Allow-Origin','*');
/* 设置响应体 */
response.send("Hello AJAX POST");
})

7.POST设置请求参数

1
2
3
xhr.send("a=100&b=200&c=300");

xhr.send('a:100&b:200&c:300');

8.设置请求头信息

1
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
1
response.setHeader('Access-Control-Allow-Headers','*')

9.接收JSON

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<div class="box"></div>
<script>
const div = document.querySelector(".box");
window.addEventListener("keydown",function(){
const xhr = new XMLHttpRequest();

xhr.open("POST","http://localhost:8030/serve");
xhr.send();
xhr.addEventListener("readystatechange",function(){
if (xhr.readyState===4){
if (xhr.status >=200 && xhr.status <300){
/* 手动转换 */
const data = JSON.parse(xhr.responseText);
div.innerHTML=data.name;
/* 自动转换 */
console.log(xhr.response);
div.innerHTML=xhr.response
}else{

}
}
})
})
1
2
3
4
5
6
7
8
9
10
11
12
app.all("/serve",(request,response)=>{
/* 设置响应头 设置允许跨域访问 */
response.setHeader('Access-Control-Allow-Origin','*');
//响应头
response.setHeader('Access-Control-Allow-Headers','*')
/* 设置响应体 */
const data = {
name:"ikun"
}
let str = JSON.stringify(data);
response.send(str);
})

10.nodemon自动重启

由于之前每次修改serve.js都要重新启动,所以我们使用nodemon

1
npm install -g nodemon
1
2
3
nodemon serve.js
//如果报错
npx nodemon serve.js

11.解决IE缓存问题

1
xhr.open("POST","http://localhost:8030/serve?t="+Date.now());

2.AJAX请求

1.请求超时和网络异常处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const div = document.querySelector(".box");
window.addEventListener("keydown",function(){
const xhr = new XMLHttpRequest();

xhr.open("POST","http://localhost:8030/delay");
xhr.send();


xhr.timeout=2000;

xhr.addEventListener("timeout",function(){
alert("网络异常");
})
xhr.addEventListener("error",function(){
alert("网络断开连接");
})


xhr.addEventListener("readystatechange",function(){
if (xhr.readyState===4){
if (xhr.status >=200 && xhr.status <300){
div.innerHTML=xhr.response;
}else{

}
}
})
})

2.取消请求

1
xhr.abort();

3.解决重复请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const btn1 = document.querySelector(".send");
const btn2 = document.querySelector(".done");
let x=null;
let isSending=false;
btn1.addEventListener("click",function(){
if (isSending) x.abort();
x= new XMLHttpRequest();
x.open("GET","http://177.0.0.1:8000/delay");
x.send();
isSending=true;
x.addEventListener("readystatechange",function(){
if (x.readyState==4){
isSending=4;
}
})
})
btn2.addEventListener('click',function(){
x.abort();
})

3.Axios

1.json-serve

npm i -g json-serve

<script src=”https://unpkg.com/axios/dist/axios.min.js">\

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.btns .btn1{
height: 20px;
line-height: 20px;
background-color: red;
width: 150px;
text-align: center;
}
.btns .btn2{
height: 20px;
line-height: 20px;
background-color: blue;
width: 150px;
text-align: center;
}
.btns .btn3{
height: 20px;
line-height: 20px;
background-color: green;
width: 150px;
text-align: center;
}

.btns .btn4{
height: 20px;
line-height: 20px;
background-color: yellow;
width: 150px;
text-align: center;
}
</style>
</head>
<body>
<h1>axios的基本使用</h1>
<div class="btns">
<button class="btn btn1">Get</button>
<button class="btn btn2">Post</button>
<button class="btn btn3">Put</button>
<button class="btn btn4">Delete</button>
</div>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
//console.log(axios);
const btns = document.querySelectorAll(".btn");

btns[0].addEventListener('click',function(){
axios({
method: 'GET',
url:"http://localhost:3000/posts/2"
}).then(response=>{
console.log(response);
})
})

btns[1].addEventListener('click',function(){
axios({
method: 'POST',
url:"http://localhost:3000/posts",
data:{
id:'3',
title:"The weather is so nice",
author:'rc'
}
}).then(response=>{
console.log(response);
})
})

btns[2].addEventListener('click',function(){
axios({
method: 'PUT',
url:"http://localhost:3000/posts/3",
data:{
title:"The weather is so nice",
author:'richu'
}
}).then(response=>{
console.log(response);
})
})

btns[3].addEventListener('click',function(){
axios({
method: 'DELETE',
url:"http://localhost:3000/posts/3",
}).then(response=>{
console.log(response);
})
})
</script>
</body>
</html>

2.axios.post等方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.btns .btn1{
height: 20px;
line-height: 20px;
background-color: red;
width: 150px;
text-align: center;
}
.btns .btn2{
height: 20px;
line-height: 20px;
background-color: blue;
width: 150px;
text-align: center;
}
.btns .btn3{
height: 20px;
line-height: 20px;
background-color: green;
width: 150px;
text-align: center;
}

.btns .btn4{
height: 20px;
line-height: 20px;
background-color: yellow;
width: 150px;
text-align: center;
}
</style>
</head>
<body>
<h1>axios的基本使用</h1>
<div class="btns">
<button class="btn btn1">Get</button>
<button class="btn btn2">Post</button>
<button class="btn btn3">Put</button>
<button class="btn btn4">Delete</button>
</div>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
const btns = document.querySelectorAll(".btn");

btns[0].addEventListener('click',function(){
axios.request({
method:'GET',
url:"http://localhost:3000/posts/2"
}).then((resonse)=>{
console.log(resonse);
})
})

btns[1].addEventListener('click',function(){
axios.post(
'http://localhost:3000/posts',
{
id:'3',
title:"The weather is so nice",
author:'rc'
}
).then(response=>{
console.log(response);
})
})
</script>
</body>
</html>

3.默认配置

1
2
3
/* 做默认配置 */
axios.defaults.method = 'GET';
axios.defaults.baseURL = 'http://localhost:3000/posts';

4.axios创建实例对象发送请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="btns">
<button class="btn btn1">Get</button>
<button class="btn btn2">Post</button>
</div>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
const btns = document.querySelector(".btn");

const ax = axios.create({
baseURL:'http://localhost:3000/posts',
timeout:2000
});

ax({
url:'/1'
}).then((resonse)=>{
console.log(resonse);
})
</script>
</body>
</html>

5.axios拦截器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
axios.interceptors.request.use(config => {
console.log("成功");
//return Promise.resolve(config);
return config;
},error => {
console.log(error);
return Promise.reject(error);
});

axios.interceptors.response.use(response => {
console.log("成功");
return response;
},error => {
console.log(error);
return Promise.reject(error);
});

axios({
method:'GET',
url:'http://localhost:3000/posts'
}).then(response=>{
console.log(response);
}).catch(reason=>{
console.log(reason);
})
</script>
</body>
</html>