技术标签: Web前端 ajax 前后端交互 javascript
AJAX:全称是Asynchronous JavaScript And XML
,即异步的JavaScript和XML。AJAX是用于前后端交互的工具,也就是说通过AJAX作为桥梁,客户端可以给服务端发送消息,也可以接收服务端的响应消息。
AJAX的两种实现方式:
XHR
:使用XMLHttpRequest对象来实现AJAXFetch
:使用Fetch API来实现AJAXXHR
和 Fetch
的区别:
功能点 | XHR | Fetch |
---|---|---|
基本的请求能力 | ||
基本的获取响应能力 | ||
监控请求进度 | ||
监控响应进度 | ||
Service Worker中是否可用 | ||
控制cookie的携带 | ||
控制重定向 | ||
请求取消 | ||
自定义referrer | ||
流 | ||
API风格 | Event |
Promise |
活跃度 | 停止更新 | 不断更新 |
由于AJAX是用于前后端交互的工具,为了更方便并深入的理解AJAX以及后续对它的实现,需要补充一下前后端交互的相关知识。
前后端交互使用的协议是HTTP协议,该协议规定了两个方面的内容:
1.传递消息的模式为「请求-响应」模式
2.传递消息的格式是纯文本格式,分为以下三部分
请求行
请求头
请求体
为了节省学习的成本,本文专注于讲解前端的内容,对于后端的部分,使用模拟的数据以及现有的工具来完成对后端的实现。
通过以下三种方式,来模拟后端,由浅入深的展开Ajax:
1.XMLHttpRequest
对象的方法
方法 | 描述 |
---|---|
abort() |
中止当前请求 |
getAllResponseHeaders() |
返回所有的响应头 |
getResponseHeader() |
返回特定的响应头 |
open() |
规定请求的方式 |
send() |
发送请求到服务器 |
setRequestHeader() |
设置请求头 |
2.XMLHttpRequest
对象的属性
属性 | 描述 |
---|---|
onreadystatechange |
定义当 readyState 属性发生变化时被调用的函数 |
readyState |
保存 XMLHttpRequest 的状态 |
responseText |
以字符串返回响应数据 |
responseXML |
以 XML 数据返回响应数据 |
status |
返回请求的状态号 |
statusText |
返回状态文本 |
现在前后端交互的文本数据,常用的是json格式的文本数据,因此这里使用json文件,来模拟后端返回的数据。
在当前页面同级目录下,新建一个test.json
,模拟后端返回的数据,内容如下
{
"name": "Bill",
"age": 18
}
1.向服务器发送请求
open(method, url, async)
:初始化一个新创建的请求,或重新初始化一个请求
method
:请求的方式,如 GET、POST等url
:服务器文件的位置async
:是否异步执行操作,异步为truevar xhr = new XMLHttpRequest();
xhr.open("GET", "test.json", true); // 创建请求,以GET请求的方式,请求服务器的test.json
xhr.send(); // 发送请求
按F12
,再刷新页面,点击Network
,再选中Fetch/XHR
,可以看到有一个test.json
文件
双击test.json
,再选中Response
,可以看到响应的数据内容就是test.json
中的内容
2.根据 XMLHttpRequest
和 HTTP
的状态,判断请求是否成功,并获取响应数据
onreadystatechange
:定义当 readyState 属性发生变化时被调用的函数(触发readystatechange事件)readyState
:XMLHttpRequest 的状态
0
:请求未初始化1
:服务器连接已建立2
:请求已接收3
:正在处理请求4
:请求已完成且响应已就绪status
: HTTP
的状态码,200-299
表示请求成功,具体状态码含义可参考 常见的HTTP状态码汇总
200
:OK403
:Forbidden404
:Not FoundresponseText
:以字符串形式返回的响应数据注:通过以上可以得出,当
readyState === 4
且status
范围在[200,300)
时,表示本次请求正常完成。
var xhr = new XMLHttpRequest();
xhr.open("GET", "test.json", true);
xhr.send();
// readyState属性发生变化时调用的函数
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
// 请求已完成且响应已就绪
if (xhr.status === 200) {
// 请求成功
console.log(JSON.parse(xhr.responseText)); // 打印服务器的响应文本
} else {
console.log(xhr.status, xhr.statusText); // 打印响应状态码和响应状态文本
console.log(xhr.responseText);
}
}
};
刷新页面,运行结果如下:
通过修改以上代码中的test.json
为test1.json
,构造请求服务器中不存在的文件,运行结果如下:
3.可以使用onload
属性代替onreadystatechange
且readyState === 4
的情况
注:onload属性表示当一个XMLHttpRequest请求完成的时候会触发load事件
var xhr = new XMLHttpRequest();
xhr.open("GET", "test.json", true);
xhr.send();
// XMLHttpRequest请求完成的时候会触发load事件
xhr.onload = function () {
// 使用正则表达式,判断xhr.status范围是否在[200,300)
if (/^2\d{2}$/.test(xhr.status)) {
console.log(JSON.parse(xhr.responseText));
} else {
console.log(xhr.status, xhr.statusText);
console.log(xhr.responseText);
}
};
调用网络接口,将模拟的数据,改为网络的真实数据。
将上面代码中的test.json
改为以下网络地址即可:
http://www.xiongmaoyouxuan.com/api/tabs
1.向网络服务器请求
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.xiongmaoyouxuan.com/api/tabs", true);
xhr.send();
// XMLHttpRequest请求完成的时候会触发load事件
xhr.onload = function () {
if (/^2\d{2}$/.test(xhr.status)) {
console.log(JSON.parse(xhr.responseText));
} else {
console.log(xhr.status, xhr.statusText);
console.log(xhr.responseText);
}
};
运行结果如下:
由于json数据过长,在此处贴出部分数据作为参照:
{
"code": 200,
"data": {
"list": [
{
"commoditiesBoardId": 0,
"id": 1,
"name": "今日推荐",
"imageUrl": "http://img1.lukou.com/static/p/fb/tab/1/20181211-151644.jpeg",
"extraData": "{\"need_banner\": 1, \"category_id\": 13, \"need_grid\": 1}",
"flowBoardId": 89,
"note": "小编精选,全场特惠 (ง •̀_•́)ง",
"gridsBoardId": 3,
"bannerBoardId": 2,
"feedsBoardId": 0,
"categoryId": 0
},
{
"commoditiesBoardId": 157,
"id": 2,
"name": "女装",
"imageUrl": "http://img1.lukou.com/static/p/fb/tab/2/20190220-155007.png",
"extraData": "{\"category_id\": 1, \"fe_category_id\": 1689}",
"flowBoardId": 75,
"note": "",
"gridsBoardId": 4,
"bannerBoardId": 0,
"feedsBoardId": 5,
"categoryId": 1689
}
]
}
}
2.对服务器返回的数据进行处理,并渲染到页面上
<!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>Document</title>
</head>
<body>
<button>点击查询商品</button>
<ul>
<li>
<p>今日推荐</p>
<img src="http://img1.lukou.com/static/p/fb/tab/1/20181211-151644.jpeg" />
</li>
</ul>
<script>
var btn = document.querySelector("button");
var ul = document.querySelector("ul");
// 注册点击事件
btn.onclick = function () {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.xiongmaoyouxuan.com/api/tabs", true);
xhr.send();
// XMLHttpRequest请求完成的时候会触发load事件
xhr.onload = function () {
if (/^2\d{2}$/.test(xhr.status)) {
var responseData = JSON.parse(xhr.responseText); // 响应数据
console.log(responseData);
render(responseData); // 渲染数据
} else {
console.log(xhr.status, xhr.statusText);
console.log(xhr.responseText);
}
};
};
// 处理获取的响应数据,并将其渲染到页面上
function render(responseData) {
var commodityList = responseData.data.list.map(function (commodity) {
return `<li>
<p>${
commodity.name}</p>
<img src="${
commodity.imageUrl}" />
</li>`;
});
console.log(commodityList);
ul.innerHTML = commodityList.join("");
}
</script>
</body>
</html>
点击按钮,运行结果如下:
json-server可以模拟服务器:下载node.js,并安装json-server,再新建一个json文件,通过json-server来运行这个json文件,此时该json文件就具备了基本的后端服务器的能力,可以完成一些基本的增删改查。
1.下载并安装node.js
,进入node
官网,选择LTS
版本点击下载安装包
node官网地址:https://nodejs.org/en
2.双击安装包,一直点击Next,完成安装
3.打开cmd,输入node -v
和 npm -v
,出现版本号则表示安装成功
4.切换镜像源至国内淘宝镜像源,提高npm
下载速度
# 设置镜像源
npm config set registry https://registry.npm.taobao.org
# 查看镜像源
npm config get registry
1.输入以下命令,安装json-server
npm install -g json-server
2.安装完成json-server以后,再新建一个test.json
文件,内容如下
{
"users": [
{
"id": 1,
"name": "Bill"
},
{
"id": 2,
"name": "Jackson"
}
],
"shopcar": ["女装", "男装", "配饰", "零食", "母婴用品", "箱包"]
}
3.打开cmd,切换路径到test.json所在路径,输入命令 json-server test.json
运行服务器,得到服务器地址如下
http://localhost:3000/users
http://localhost:3000/shopcar
4.当前页面index.html
,输入以下内容
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:3000/users", true); // 向json-server服务器发送请求
xhr.send();
xhr.onload = function () {
if (/^2\d{2}$/.test(xhr.status)) {
console.log(JSON.parse(xhr.responseText));
} else {
console.log(xhr.status, xhr.statusText);
console.log(xhr.responseText);
}
};
5.由于json-server
会和Live Server
冲突,所以不能使用Live Server
打开浏览器,可以下载插件Preview on Web Server
,使用该插件打开浏览器。
右键点击vscode-preview-server:Launch on browser
,打开页面。
打开控制台,运行结果如下,说明获取到了服务器返回的数据:
请求方式 | 描述 |
---|---|
GET |
获取数据 |
POST |
提交数据 |
PUT |
更新全部数据 |
PATCH |
更新部分数据 |
DELETE |
删除数据 |
HEAD |
获取服务器头信息 |
OPTIONS |
获取服务器设备信息 |
CONNECT |
保留请求方式 |
在3.4
节使用json-server
模拟服务器的基础之上,来模拟如下5种常见的请求方式。
test.json
的内容为3.4.2
节中的内容,在test.json
所在路径下,输入以下命令启动json-server
:
json-server test.json --watch
GET
请求:用于获取服务器的数据。
GET
请求的方式有两种:
GET
请求,获取服务器地址的全部数据GET
请求,获取服务器地址的特定数据1.不带参数的GET
请求,获取服务器全部数据
<!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>Document</title>
</head>
<body>
<button>GET</button>
<script>
var btn = document.querySelector("button");
btn.onclick = function () {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:3000/users", true); // 创建一个GET请求
xhr.send();
xhr.onload = function () {
if (/^2\d{2}$/.test(xhr.status)) {
console.log(JSON.parse(xhr.responseText));
} else {
console.log(xhr.status, xhr.statusText);
console.log(xhr.responseText);
}
};
};
</script>
</body>
</html>
右键点击vscode-preview-server:Launch on browser
,打开页面并点击GET按钮,运行结果如下:
2.带参数的GET
请求,获取服务器地址的特定数据
如需获取特定数据,在原地址上加上key=value
格式的数据即可。
key=value
:获取单个特定数据key=value&key=value
:获取多个特定数据key=value
:比如向服务器请求获取id=1
的数据,可以修改http://localhost:3000/users
为http://localhost:3000/users?id=1
,运行结果如下:
key=value&key=value
:比如向服务器请求获取id=1
以及id=2
的数据,可以修改http://localhost:3000/users
为http://localhost:3000/users?id=1&id=2
,运行结果如下:
POST
请求:用于向服务器提交数据。
POST
提交文本数据有两种格式:
key=value
格式的字符串,设置content-type为application/x-www-form-urlencoded
json
格式的字符串,设置content-type为application/json
1.使用form
编码格式的字符串,向服务器提交数据
<!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>Document</title>
</head>
<body>
<button>POST</button>
<script>
var btn = document.querySelector("button");
btn.onclick = function () {
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:3000/users", true); // 创建一个POST请求
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded"); // 设置请求头的content-type属性值为form编码
data = "name=Michael&age=18"; // form编码格式的数据
xhr.send(data); // 发送数据
xhr.onload = function () {
if (/^2\d{2}$/.test(xhr.status)) {
console.log(JSON.parse(xhr.responseText));
} else {
console.log(xhr.status, xhr.statusText);
console.log(xhr.responseText);
}
};
};
</script>
</body>
</html>
打开页面并点击POST按钮,运行结束后,发现test.json
文件新增了刚刚提交的数据
2.使用json
格式的字符串,向服务器提交数据
<!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>Document</title>
</head>
<body>
<button>POST</button>
<script>
var btn = document.querySelector("button");
btn.onclick = function () {
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:3000/users", true); // 创建一个POST请求
xhr.setRequestHeader("content-type", "application/json"); // 设置请求头的content-type属性值为json格式
data = JSON.stringify({
name: "Ada", age: 18 }); // json格式的字符串
xhr.send(data); // 发送数据
xhr.onload = function () {
if (/^2\d{2}$/.test(xhr.status)) {
console.log(JSON.parse(xhr.responseText));
} else {
console.log(xhr.status, xhr.statusText);
console.log(xhr.responseText);
}
};
};
</script>
</body>
</html>
打开页面并点击POST按钮,运行结束后,发现test.json
文件新增了刚刚提交的数据
PUT
请求:用于更新服务器的数据,覆盖式地更新数据,也就是更新全部数据。
<!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>Document</title>
</head>
<body>
<button>PUT</button>
<script>
var btn = document.querySelector("button");
btn.onclick = function () {
var xhr = new XMLHttpRequest();
xhr.open("PUT", "http://localhost:3000/users/4", true); // 创建一个PUT请求,请求更新id为4的数据
xhr.setRequestHeader("content-type", "application/json"); // 设置请求头的content-type属性值为json格式
data = JSON.stringify({
age: 28 }); // 更新age
xhr.send(data); // 发送数据
xhr.onload = function () {
if (/^2\d{2}$/.test(xhr.status)) {
console.log(JSON.parse(xhr.responseText));
} else {
console.log(xhr.status, xhr.statusText);
console.log(xhr.responseText);
}
};
};
</script>
</body>
</html>
注:更新的路径要写准确指定,
http://localhost:3000/users/4
中的/4
表示id为4的数据
打开页面并点击PUT按钮,运行结束后,发现test.json
文件更新了刚刚发送的age数据,而且是覆盖式更新,以前的name属性数据被覆盖不见了。
PATCH
请求:用于更新服务器的数据,补丁式地更新数据,也就是更新部分数据。
<!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>Document</title>
</head>
<body>
<button>PATCH</button>
<script>
var btn = document.querySelector("button");
btn.onclick = function () {
var xhr = new XMLHttpRequest();
xhr.open("PATCH", "http://localhost:3000/users/3", true); // 创建一个PATCH请求,请求更新id为3的数据
xhr.setRequestHeader("content-type", "application/json"); // 设置请求头的content-type属性值为json格式
data = JSON.stringify({
age: 28 }); // 更新age
xhr.send(data); // 发送数据
xhr.onload = function () {
if (/^2\d{2}$/.test(xhr.status)) {
console.log(JSON.parse(xhr.responseText));
} else {
console.log(xhr.status, xhr.statusText);
console.log(xhr.responseText);
}
};
};
</script>
</body>
</html>
打开页面并点击PATCH按钮,运行结束后,发现test.json
文件更新了刚刚发送的age数据,而且是补丁式更新,以前的name属性数据不会被覆盖,依然保持原样。
DELETE
请求:用于删除服务器的数据。
<!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>Document</title>
</head>
<body>
<button>DELETE</button>
<script>
var btn = document.querySelector("button");
btn.onclick = function () {
var xhr = new XMLHttpRequest();
xhr.open("DELETE", "http://localhost:3000/users/4", true); // 创建一个DELETE请求,请求删除id为4的数据
xhr.send(); // 发送请求
xhr.onload = function () {
if (/^2\d{2}$/.test(xhr.status)) {
console.log(JSON.parse(xhr.responseText));
} else {
console.log(xhr.status, xhr.statusText);
console.log(xhr.responseText);
}
};
};
</script>
</body>
</html>
打开页面并点击DELETE按钮,运行结束后,发现test.json
文件中id为4的数据已被删除。
注:要学习Fetch
,需要先学习ES6
中的Promise
以及async
和await
.
使用Fetch
进行前后端交互,是通过fetch()
方法发起获取资源的请求,它返回一个 promise
,这个 promise
会在请求响应后被 resolve
,并传回 Response
对象。
Fetch API包括以下部分:
Headers
接口:表示请求头或响应头的信息,允许对 HTTP 请求和响应头执行各种操作。Request
接口:表示资源请求Response
接口:表示请求的响应数据fetch()
方法:用于发起获取资源的请求Headers
对象的方法:
方法 | 描述 |
---|---|
Headers.append() |
给现有的header添加一个值 |
Headers.set() |
替换现有的header的值 |
Headers.get() |
获取指定header的全部值 |
Headers.delete() |
删除指定header |
Request
对象的属性:
属性 | 描述 |
---|---|
Request.method |
请求方式 |
Request.url |
请求的 URL |
Request.headers |
请求相关的Headers对象 |
Request.credentials |
请求的证书 |
Request.mode |
请求的模式 |
Request.cache |
请求的缓存模式 |
Response
对象的属性:
属性 | 描述 |
---|---|
Response.headers |
Response所关联的Headers对象 |
Response.status |
Response的状态码 |
Response.statusText |
与该Response状态码一致的状态信息 |
Response.url |
Response的URL |
Response
对象实例的方法:
方法 | 描述 |
---|---|
Response.json() |
将响应体解析为json对象 |
Response.text() |
将响应体解析为字符串 |
Response.formData() |
将响应体解析为fromData表单对象 |
Response.blob() |
将响应体解析为二进制blob对象 |
Response.arrayBuffer() |
将响应体解析为二进制arrayBuffer对象 |
fetch()
方法:
Promise<Response> fetch(input[, init]);
input
:定义要获取的资源,这可能是:
init
:一个配置项对象,包括所有对请求的设置。可选的参数有:
method
: 请求方式headers
: 请求头信息body
: 请求体信息mode
: 请求的模式credentials
: 请求的证书cache
: 请求的缓存模式redirect
: 如何处理重定向模式依然是使用json-server
模拟服务器的情况下,来模拟GET、POST、PUT、PATCH、DELETE,这5种常见的请求方式。
test.json
的内容为3.4.2
节中的内容,在test.json
所在路径下,打开cmd
输入以下命令启动json-server
:
json-server test.json --watch
由于请求是异步的,所以此处使用async
和await
。
<!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>Document</title>
</head>
<body>
<button>GET</button>
<script>
const btn = document.querySelector("button");
btn.onclick = async function () {
const resp = await fetch("http://localhost:3000/users"); // 等待拿到响应头,拿到响应头promise就完成了
const data = await resp.json(); // 等待解析响应体,使用json格式解析响应体
console.log(resp); // 响应头
console.log(data); // 响应体
};
</script>
</body>
</html>
右键点击vscode-preview-server:Launch on browser
,打开页面并点击GET按钮,运行结果如下:
以下两行代码,还可以精简为一行:
const resp = await fetch("http://localhost:3000/users"); // 等待拿到响应头,拿到响应头promise就完成了
const data = await resp.json(); // 等待解析响应体,使用json格式解析响应体
精简后:
const data = await fetch("http://localhost:3000/users").then(resp => resp.json());
<!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>Document</title>
</head>
<body>
<button>POST</button>
<script>
const btn = document.querySelector("button");
btn.onclick = async function () {
// 请求的信息
init = {
method: "POST",
headers: {
"content-type": "application/json" },
body: JSON.stringify({
name: "Ada", age: 18 })
};
// 发送请求
const data = await fetch("http://localhost:3000/users", init).then(resp => resp.json());
console.log(data);
};
</script>
</body>
</html>
打开页面并点击POST按钮,运行结果如下:
<!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>Document</title>
</head>
<body>
<button>PUT</button>
<script>
const btn = document.querySelector("button");
btn.onclick = async function () {
// 请求的信息
init = {
method: "PUT",
headers: {
"content-type": "application/json" },
body: JSON.stringify({
age: 28 })
};
// 发送请求
const data = await fetch("http://localhost:3000/users/3", init).then(resp => resp.json());
console.log(data);
};
</script>
</body>
</html>
打开页面并点击PUT按钮,运行结果如下:
<!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>Document</title>
</head>
<body>
<button>PATCH</button>
<script>
const btn = document.querySelector("button");
btn.onclick = async function () {
// 请求的信息
init = {
method: "PATCH",
headers: {
"content-type": "application/json" },
body: JSON.stringify({
age: 28 })
};
// 发送请求
const data = await fetch("http://localhost:3000/users/2", init).then(resp => resp.json());
console.log(data);
};
</script>
</body>
</html>
打开页面并点击PATCH按钮,运行结果如下:
<!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>Document</title>
</head>
<body>
<button>DELETE</button>
<script>
const btn = document.querySelector("button");
btn.onclick = async function () {
// 请求的信息
init = {
method: "DELETE" };
// 发送请求
const data = await fetch("http://localhost:3000/users/3", init).then(resp => resp.json());
console.log(data);
};
</script>
</body>
</html>
打开页面并点击DELETE按钮,运行结果如下:
Axios:是一个基于promise封装的第三方HTTP库,可以用在浏览器和node.js中。
Axios网址:https://www.npmjs.com/package/axios
打开Axios网址,可以看到有一个目录,目录中包含了Axios的安装教程、API使用教程以及例子等等。
1.安装:安装方法有很多种,这里我们通过引用外部js文件的方式,引入axios库。
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
2.API使用方法
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
其中config配置可参考以下内容:
// Send a POST request
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
依然是使用json-server
模拟服务器的情况下,来模拟GET、POST、PUT、PATCH、DELETE,这5种常见的请求方式。
test.json
的内容为3.4.2
节中的内容,在test.json
所在路径下,打开cmd
输入以下命令启动json-server
:
json-server test.json --watch
1.GET请求
<!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>Document</title>
<!-- 引入axios库 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
</head>
<body>
<button>GET</button>
<script>
const btn = document.querySelector("button");
btn.onclick = async function () {
await axios
.get("http://localhost:3000/users") // 发送GET请求
.then(res => {
console.log(res); // 响应的全部内容
console.log(res.data); // 响应的数据内容
})
.catch(err => {
console.log(err);
});
};
</script>
</body>
</html>
右键点击vscode-preview-server:Launch on browser
,打开页面并点击GET按钮,运行结果如下:
如果要发送带参数的GET请求,可以修改axios.get()
为以下内容:
// 获取id=1的数据
axios.get("http://localhost:3000/users", {
params: {
id: 1
}
});
2.POST请求
<!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>Document</title>
<!-- 引入axios库 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
</head>
<body>
<button>POST</button>
<script>
const btn = document.querySelector("button");
btn.onclick = async function () {
await axios
.post("http://localhost:3000/users", {
name: "Ada", age: 18 }) // 发送POST请求
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
};
</script>
</body>
</html>
如果要使用form编码的格式,可以修改axios.post()
为以下内容:
axios.post("http://localhost:3000/users", "name=Michael&age=18")
3.PUT请求
<!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>Document</title>
<!-- 引入axios库 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
</head>
<body>
<button>PUT</button>
<script>
const btn = document.querySelector("button");
btn.onclick = async function () {
await axios
.put("http://localhost:3000/users/3", {
age: 28 }) // 发送PUT请求
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
};
</script>
</body>
</html>
4.PATCH请求
<!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>Document</title>
<!-- 引入axios库 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
</head>
<body>
<button>PATCH</button>
<script>
const btn = document.querySelector("button");
btn.onclick = async function () {
await axios
.patch("http://localhost:3000/users/2", {
age: 28 }) // 发送PATCH请求
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
};
</script>
</body>
</html>
5.DELETE请求
<!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>Document</title>
<!-- 引入axios库 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
</head>
<body>
<button>DELETE</button>
<script>
const btn = document.querySelector("button");
btn.onclick = async function () {
await axios
.delete("http://localhost:3000/users/3") // 发送DELETE请求
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
};
</script>
</body>
</html>
文章浏览阅读1k次。通过使用ajax方法跨域请求是浏览器所不允许的,浏览器出于安全考虑是禁止的。警告信息如下:不过jQuery对跨域问题也有解决方案,使用jsonp的方式解决,方法如下:$.ajax({ async:false, url: 'http://www.mysite.com/demo.do', // 跨域URL ty..._nginx不停的xhr
文章浏览阅读2k次。关于在 Oracle 中配置 extproc 以访问 ST_Geometry,也就是我们所说的 使用空间SQL 的方法,官方文档链接如下。http://desktop.arcgis.com/zh-cn/arcmap/latest/manage-data/gdbs-in-oracle/configure-oracle-extproc.htm其实简单总结一下,主要就分为以下几个步骤。..._extproc
文章浏览阅读1.5w次。linux下没有上面的两个函数,需要使用函数 mbstowcs和wcstombsmbstowcs将多字节编码转换为宽字节编码wcstombs将宽字节编码转换为多字节编码这两个函数,转换过程中受到系统编码类型的影响,需要通过设置来设定转换前和转换后的编码类型。通过函数setlocale进行系统编码的设置。linux下输入命名locale -a查看系统支持的编码_linux c++ gbk->utf8
文章浏览阅读750次。今天准备从生产库向测试库进行数据导入,结果在imp导入的时候遇到“ IMP-00009:导出文件异常结束” 错误,google一下,发现可能有如下原因导致imp的数据太大,没有写buffer和commit两个数据库字符集不同从低版本exp的dmp文件,向高版本imp导出的dmp文件出错传输dmp文件时,文件损坏解决办法:imp时指定..._imp-00009导出文件异常结束
文章浏览阅读143次。当下是一个大数据的时代,各个行业都离不开数据的支持。因此,网络爬虫就应运而生。网络爬虫当下最为火热的是Python,Python开发爬虫相对简单,而且功能库相当完善,力压众多开发语言。本次教程我们爬取前程无忧的招聘信息来分析Python程序员需要掌握那些编程技术。首先在谷歌浏览器打开前程无忧的首页,按F12打开浏览器的开发者工具。浏览器开发者工具是用于捕捉网站的请求信息,通过分析请求信息可以了解请..._初级python程序员能力要求
文章浏览阅读7.6k次,点赞2次,收藏6次。@Service标注的bean,类名:ABDemoService查看源码后发现,原来是经过一个特殊处理:当类的名字是以两个或以上的大写字母开头的话,bean的名字会与类名保持一致public class AnnotationBeanNameGenerator implements BeanNameGenerator { private static final String C..._@service beanname
文章浏览阅读6.9w次,点赞73次,收藏463次。1.前序创建#include<stdio.h>#include<string.h>#include<stdlib.h>#include<malloc.h>#include<iostream>#include<stack>#include<queue>using namespace std;typed_二叉树的建立
文章浏览阅读7.1k次。在Asp.net上使用Excel导出功能,如果文件名出现中文,便会以乱码视之。 解决方法: fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);_asp.net utf8 导出中文字符乱码
文章浏览阅读2.1k次,点赞4次,收藏23次。第一次实验 词法分析实验报告设计思想词法分析的主要任务是根据文法的词汇表以及对应约定的编码进行一定的识别,找出文件中所有的合法的单词,并给出一定的信息作为最后的结果,用于后续语法分析程序的使用;本实验针对 PL/0 语言 的文法、词汇表编写一个词法分析程序,对于每个单词根据词汇表输出: (单词种类, 单词的值) 二元对。词汇表:种别编码单词符号助记符0beginb..._对pl/0作以下修改扩充。增加单词
文章浏览阅读773次。我在使用adb.exe时遇到了麻烦.我想使用与bash相同的adb.exe shell提示符,所以我决定更改默认的bash二进制文件(当然二进制文件是交叉编译的,一切都很完美)更改bash二进制文件遵循以下顺序> adb remount> adb push bash / system / bin /> adb shell> cd / system / bin> chm..._adb shell mv 权限
文章浏览阅读6.8k次,点赞12次,收藏125次。1. 单目相机标定引言相机标定已经研究多年,标定的算法可以分为基于摄影测量的标定和自标定。其中,应用最为广泛的还是张正友标定法。这是一种简单灵活、高鲁棒性、低成本的相机标定算法。仅需要一台相机和一块平面标定板构建相机标定系统,在标定过程中,相机拍摄多个角度下(至少两个角度,推荐10~20个角度)的标定板图像(相机和标定板都可以移动),即可对相机的内外参数进行标定。下面介绍张氏标定法(以下也这么称呼)的原理。原理相机模型和单应矩阵相机标定,就是对相机的内外参数进行计算的过程,从而得到物体到图像的投影_相机-投影仪标定
文章浏览阅读2.2k次。文章目录Wayland 架构Wayland 渲染Wayland的 硬件支持简 述: 翻译一篇关于和 wayland 有关的技术文章, 其英文标题为Wayland Architecture .Wayland 架构若是想要更好的理解 Wayland 架构及其与 X (X11 or X Window System) 结构;一种很好的方法是将事件从输入设备就开始跟踪, 查看期间所有的屏幕上出现的变化。这就是我们现在对 X 的理解。 内核是从一个输入设备中获取一个事件,并通过 evdev 输入_wayland