Ajax

Ajax

liohi

HTTP

HTTP(HyperText Transport Protocol)协议,也就是超文本传输协议,详细规定了浏览器和万维网服务器之间相互通信的规则

请求报文

格式与参数

1
2
3
4
5
6
7
行	POST /s?ie=utf-8 HTTP/1.1
头 HOST: herrick.3vhost.net
Cookie: name=herrick
Content-type: application/x-www-form-urlencoded
User-Agent: chorome-83
空行

响应报文

1
2
3
4
5
6
7
8
9
10
11
12
行	HTTP/1.1 200 OK
头 Content-Type: text/html;charset=utf-8
Content-length: 2048
Content-encoding: gzip
空行
体 <html>
<head>
</head>
<body>
<h1>标题</h1>
</body>
</html>
  • 404
  • 403
  • 401
  • 500 ……

express 框架

express框架是一个简介而灵活的node.js Web应用框架,提供了一系列强大的特性创建各种 Web 应用和丰富的HTTP工具。

使用express框架可以快速搭建一个完整功能的网站,所以我们可以利用express模拟一个后端服务的环境

  • 首先在项目包里利用npm下载express

  • npm i express
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22

    - 创建一个`server.js`文件

    - ```javascript
    //引入express
    const { response } = require("express");
    const express = require("express");

    //创建应用对象
    const app = express();

    //创建路由规则
    //request对请求报文封装
    //respose对相应报文封装
    app.get("/", (request, response) => {
    //设置响应
    response.send("hello express");
    });

    app.listen(8000, () => {
    console.log("服务已经启动,8000端口监听中....");
    });
  • 然后node server.js,注意路径需要cd到当前包下

此时服务已经启动,控制台显示服务已经启动,8000端口监听中....,网址输入localhost:8000能够看到hello express

原生 Ajax

创建两个文件,一个HTML和一个server.js

server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//.引入express
const express = require("express");

//.创建应用对象
const app = express();

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

//.监听端口启动服务
app.listen(8000, () => {
console.log("服务已经启动,8000端口监听中....");
});

.html

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
<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>AJAX GEt 请求</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="" />
</head>

<body>
<button>点击发送请求</button>
<div id="result"></div>
<!--[if lt IE 7]>
<p class="browsehappy">
You are using an <strong>outdated</strong> browser. Please
<a href="#">upgrade your browser</a> to improve your experience.
</p>
<![endif]-->

<script>
//获取button元素
const btn = document.getElementsByTagName("button")[0];
const result = document.getElementById("result");
//绑定时间
btn.onclick = function () {
//1.创建对象
const xhr = new XMLHttpRequest();
//2.初始化,设置请求方法和 url
xhr.open("GET", "http://localhost:8000/server");
//3.发送
xhr.send();
//4.事件绑定 处理服务端返回的结果
// on when 当……的时候
//readystate 是 xhr 对象中的属性,表示状态0 1 2 3 4
//change 改变
xhr.onreadystatechange = function () {
//判断
if (xhr.readyState === 4) {
//判断响应状态码 200 404 403 401 500
//2** 成功
if (xhr.status >= 200 && xhr.status < 300) {
//处理结果 行 头 空行 体
//1.响应行
console.log(xhr.status); //状态码
console.log(xhr.statusText); //状态字符串
console.log(xhr.getAllResponseHeaders()); //所有响应头
console.log(xhr.response); //响应体

result.innerHTML = xhr.response;
} else {
}
}
};
console.log("test");
};
</script>
</body>
<style>
#result {
width: 300px;
height: 200px;
border: solid 1px black;
}
</style>
</html>

实现效果如下:

点击发送请求会在显示框内打印出响应体,同时在控制台显示请求信息

以上就完成了一个简单的GET请求

接下来向服务端发起一个POST请求

满足需求是:当鼠标移到显示框的时候,显示框能显示到服务端发来的响应体

修改HTML文件

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
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]> <html class="no-js"> <!--<![endif]-->
<html>

<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>
AJAX GEt 请求
</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>

<body>
<button>
点击发送请求
</button>
<div id="result"></div>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
<![endif]-->

<script>
const result = document.getElementById('result');

result.addEventListener("mousemove", function () {
const xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8000/server")
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
result.innerHTML = xhr.response;
}
}
}

})
</script>
</body>
<style>
#result {
width: 300px;
height: 200px;
border: solid 1px black;
}
</style>

</html>

但是此时如果将鼠标移动到框内,控制台会报错No 'Access-Control-Allow-Origin' header is present on the requested resource.因为服务段没有与之匹配的响应规则。此时服务端的规则还是上一小节的GET,所以需要向服务端server.js添加以下规则:

1
2
3
4
5
6
app.get("/server", (request, response) => {
//设置响应头,设置允许跨域
response.setHeader("Access-Control-Allow-Origin", "*");
//设置响应体
response.send("hello express");
});

重新启动服务node server.js,再次在html页面滑动鼠标到框内,显示响应体成功

POST 请求设置参数

POST请求设置参数,请求体是在send()里设置的,参数的形式任意,但是需要服务端能够处理

比如xhr.send('a=100&b=200&c=300'),或者可以xhr.send('a:100&b:200&c:300'),或者直接xhr.send('12341414141'),只要服务端能够处理就可

Ajax 设置请求头信息

设置请求信息,只需要在open()后面调用一个方法setRequestHeader例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script>
const result = document.getElementById("result");

result.addEventListener("mousemove", function () {
const xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8000/server");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//其中Content-Type是设置请求体内容的类型,后面的内容是参数查询字符串的类型,固定写法
//比如可以自己设定一个头信息
xhr.setRequestHeader("name", "herrick.3vhost");
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
result.innerHTML = xhr.response;
}
}
};
});
</script>

服务端响应json数据

实际工作中服务端返回数据多数情况都是以json格式发送,那么返回的结果应该怎么处理很重要

首先向server.js添加下面代码all代表接收所有类型的请求

1
2
3
4
5
6
7
8
9
10
11
app.all("/json-server", (request, response) => {
//设置响应头,设置允许跨域
response.setHeader("Access-Control-Allow-Origin", "*");
//设置响应体
const data = {
name: "herrick",
};
//由于send只能发送jsom或者bufferl类型,所以需要对字符串进行一个转换
let str = JSON.stringify(data);
response.send(str);
});

html文件<script>标签内容如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script>
const result = document.getElementById("result");
//绑定键盘按下时间
window.onkeydown = function () {
//发送请求
const xhr = new XMLHttpRequest();
//初始化;
xhr.open("GET", "http://localhost:8000/json-server");
//发送
xhr.send();
//事件绑定
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
result.innerHTML = xhr.response;
}
}
};
};
</script>

当键盘按下之后,就能接收到服务端传来的json数据

此时数据为一个json格式字符串,我们需要将其变成一个对象

可以手动转换

1
2
let data = JSON.parse(xhr.response); //然后就可以使用data里面的数据
result.innerHTML = data.name;

更推荐自动转换

1
2
xhr.responseType = 'json' //然后就可以直接使用数据 result.innerHTML =
xhr.response.name

nodemon 工具

作用:自动检测文件改变重启服务

前提:node.js

1
2
3
4
5
6
7
8
9
10
11
npm i -g nodemon
//再使用nodemon重启服务
nodemon server.js
//部分用户会出现错误< nodemon : 无法加载文件XXX,因为在此系统上禁止运行脚本。>原因是powershell权限不够
//解决方法
1. win+R输入powershell
2. 输入start-proces s PowerShell -verb runas 进入管理员权限
3. 管理员身份输入set-Exe cutionPolicy RemoteSigned 选择y
4. 再次nodemon server.js 服务启动

nodemon启动服务后修改服务端代码后就无需重启服务

Ajax-IE 缓存问题解决

问题描述:IE 浏览器会对 Ajax 的请求结果做一个缓存,导致再次发送请求时走的时本地缓存而不是服务器返回的数据,导致最新数据不能接收。

解决方案:修改open()

1
2
xhr.open('GET', 'http://localhost:8000/json-server?t='+Date.now);
// Date.now是一个时间戳,所以每次都会发送不同请求,浏览器就会判定为两次请求,也就解决了缓存问题

Ajax 请求超时和网络异常

例如:请求两秒为超时

1
2
3
4
5
6
7
8
9
10
//超时时间为2s
xhr.timeout = 2000;
//超时回调
xhr.ontimeout = function(){
alert("网络超时,请稍后重试!");
}
//异常回调
xhr.onerror = function(){
alert("网络异常!");
}

Ajax 取消请求

调用XMLHttpRequestabort()

例如:

1
2
3
4
//按下按键取消请求
btn.onclick = function(){
xhr.abort();
}

Ajax 重复发送请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script>
let isSending = false; //是否正在发送Ajax请求
btn.onclick = function(){
if(isSending)x.abort(); //如果正在发送,则取消该请求,创建一个新的请求
x = new XMLHttpRrequest();
isSending = true;
x.open("GET","http://localhost:8000");
x.send();
x.onreadystatechange = function(){
if(x.readyState === 4){
isSending = false; //修改标识变量
}
}
}
</script>

Axios发送Ajax请求

  • 首先配置server.js
1
2
3
4
5
6
7
8
9
10
11
12
//axios 服务
app.all("/axios-server", (request, response) => {
//设置响应头,设置允许跨域
response.setHeader("Access-Control-Allow-Origin", "*");
//设置响应体
const data = {
name: "herrick",
};
//由于send只能发送jsom或者bufferl类型,所以需要对字符串进行一个转换
let str = JSON.stringify(data);
response.send(str);
});
  • HTML引用Axios资源
1
2
3
4
<script
crossorigin="anonymous"
src="https://cdn.bootcdn.net/ajax/libs/axios/1.1.3/axios.js"
></script>
  • GET请求

1
2
3
4
5
6
7
8
9
10
11
<script>
const btns = document.querySelectorAll('button'); btns[0].onclick = function
(){" "}
{axios.get("http://localhost:8000/axios-server", {
//url 参数
params: {
id: 10,
vip: 2,
},
})}
</script>

此时控制台可以看到传递的参数

  • 标题: Ajax
  • 作者: liohi
  • 创建于 : 2023-04-16 16:55:37
  • 更新于 : 2023-04-19 22:26:59
  • 链接: https://liohi.github.io/2023/04/16/Ajax/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
 评论