本文不涉及然和的介绍和其它的相关内容,只是博主简单的记录一下封装 POST 的代码:

myAjax.js:

const obj2str = (obj) => {
// 如果没有传参, 为了添加随机因子,必须自己创建一个对象
obj = obj || {};
obj.t = new Date().getTime();
let res = [];
for (let key in obj) {
// 在URL中是不可以出现中文的, 如果出现了中文需要转码
// 可以调用encodeURIComponent方法
// URL中只可以出现字母/数字/下划线/ASCII码
res.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]));
}
return res.join("&");
}

const ajax = (type, url, obj, timeout, success, error) => {
// 0.将对象转换为字符串
// key=value&key=value;
let str = obj2str(obj);

// 1.创建一个异步对象
let xmlHttp, timer;

// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}

// 2.设置请求方式和请求地址
/*
method:请求的类型;GET 或 POST
url:文件在服务器上的位置
async:true(异步)或 false(同步)
*/
if (type === "GET") {
xmlHttp.open(type, url + "?" + str, true);
// 3.发送请求
xmlHttp.send();
} else {
xmlHttp.open(type, url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send(str);
}

// 4.监听状态的变化
xmlHttp.onreadystatechange = (event) => {
/*
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
*/
if (xmlHttp.readyState === 4) {
clearInterval(timer);
// 判断是否请求成功
if (xmlHttp.status >= 200 && xmlHttp.status < 300 ||
xmlHttp.status === 304) {
// 5.处理返回的结果
// console.log("接收到服务器返回的数据");
success(xmlHttp);
} else {
// console.log("没有接收到服务器返回的数据");
error(xmlHttp);
}
}
}

// 判断外界是否传入了超时时间
if (timeout) {
timer = setInterval(() => {
console.log("中断请求");
xmlHttp.abort();
clearInterval(timer);
}, timeout);
}
}

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax-post</title>
<script src="myAjax.js"></script>
<script>
window.onload = function () {
let oBtn = document.querySelector("button");
oBtn.onclick = function () {
ajax("POST", "ajax-post.php", {
"userName": "BNTang",
"userPwd": "123"
}, 3000, (xhr) => {
alert(xhr.responseText)
}, () => {
console.log("请求失败");
});
}
}
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>

ajax-post.php:

<?php
echo $_POST["userName"];
echo $_POST["userPwd"];
?>