https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest
<!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>
<div>
<button onclick="testGet()">GET 请求</button>
<button onclick="testPost()">POST 请求</button>
<button onclick="testPut()">PUT 请求</button>
<button onclick="testDelete()">DELETE 请求</button>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.24.0/axios.js"></script>
<script>
/*
使用 XHR 封装发送 ajax 请求的通用函数
返回值: promise
参数为配置对象
url: 请求地址
params: 包含所有 query 请求参数的对象 {name: tom, age: 12} ==> name=tom&age=12
data: 包含所有请求体参数数据的对象
method: 为请求方式
*/
function axios({ url, method = "GET", params = {}, data = {} }) {
// 返回一个promise对象
return new Promise((resolve, reject) => {
// 处理method(转大写)
method = method.toUpperCase();
// 处理query参数(拼接到url上) id=1&xxx=abc
/*
{
id: 1,
xxx: 'abc'
}
*/
let queryString = "";
Object.keys(params).forEach((key) => {
// queryString += `${key}=${params[key]}&`;
queryString += key + "=" + params[key] + "&";
});
if (queryString) {
// id=1&xxx=abc&
// 去除最后的&
queryString = queryString.substring(0, queryString.length - 1);
// 接到url
url += "?" + queryString;
}
// 1. 执行异步ajax请求
// 创建xhr对象
const request = new XMLHttpRequest();
// 打开连接(初始化请求, 没有请求)
request.open(method, url, true);
// 发送请求
if (method === "GET" || method === "DELETE") {
request.send();
} else if (method === "POST" || method === "PUT") {
request.setRequestHeader(
"Content-Type",
"application/json;charset=utf-8"
); // 告诉服务器请求体的格式是json
request.send(JSON.stringify(data)); // 发送json格式请求体参数
}
// 绑定状态改变的监听
request.onreadystatechange = function () {
// 如果请求没有完成, 直接结束
if (request.readyState !== 4) {
return;
}
// 如果响应状态码在[200, 300)之间代表成功, 否则失败
const { status, statusText } = request;
// 2.1. 如果请求成功了, 调用resolve()
if (status >= 200 && status <= 299) {
// 准备结果数据对象response
const response = {
data: JSON.parse(request.response),
status,
statusText,
};
resolve(response);
} else {
// 2.2. 如果请求失败了, 调用reject()
reject(new Error("request error status is " + status));
}
};
});
}
function testGet() {
axios({
url: "http://localhost:3000/comments",
// url: 'http://localhost:3000/comments2',
params: { id: 3 },
})
.then((response) => {
console.log("get success", response.data, response);
})
.catch((err) => {
alert(err.message);
});
}
function testPost() {
axios({
url: "http://localhost:3000/comments",
// url: 'http://localhost:3000/comments2',
method: "POST",
data: { body: "aaaa", postId: 2 },
})
.then((response) => {
console.log("post success", response.data, response);
})
.catch((error) => {
alert(error.message);
});
}
function testPut() {
axios({
url: "http://localhost:3000/comments/3",
method: "put",
data: { body: "ndkasj", postId: 2 },
})
.then((res) => {
console.log("put success", res.data, res);
})
.catch((err) => {
alert(err.message);
});
}
function testDelete() {
axios({
url: "http://localhost:3000/comments/1",
method: "delete",
params: {
body: "some comment",
},
})
.then((response) => {
console.log("delete success", response.data, response);
})
.catch((error) => {
alert(error.message);
});
}
</script>
</body>
</html>