原生JS模拟JQuery封装Ajax

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>原生JS模拟JQuery封装Ajax</title>
<script src="./mock-min.js"></script>
</head>

<body>
<button id="btn">异步发送请求</button>
<p id="oP"></p>
<script>
btn.onclick = function(){
ajax(data);
}
// data作为参数传入我们下面封装的函数
let data = {
type: 'get',
//数据
data: {
user: "xiejie",
pass: '123456',
age: 18,
},
//回调函数
success: function (data) {
console.log(data);
document.getElementById('oP').innerHTML = data;
},
error:function(err){
console.log(err);
},
// 异步发送请求
async: true,
// 发送请求的url
url: 'getStudent'
}
// 辅助函数,把传进来的对象拼接成url的字符串
function toData(obj) {
if (obj === null) {
return obj;
}
let arr = [];
for (let i in obj) {
let str = i + "=" + obj[i];
arr.push(str);
}
return arr.join("&");
}
// 封装Ajax
function ajax(obj) {
//指定提交方式的默认值
obj.type = obj.type || "get";
//设置是否异步,默认为true(异步)
obj.async = obj.async || true;
//设置数据的默认值
obj.data = obj.data || null;
// 根据不同的浏览器创建XHR对象
let xhr = null;
if (window.XMLHttpRequest) {
// 非IE浏览器
xhr = new XMLHttpRequest();
} else {
// IE浏览器
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// 区分get和post,发送HTTP请求
if (obj.type === "post") {
xhr.open(obj.type, obj.url, obj.async);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
let data = toData(obj.data);
xhr.send(data);
} else {
//get test.php?xx=xx&aa=xx
let url = obj.url + "?" + toData(obj.data);
xhr.open(obj.type, url, obj.async);
xhr.send();
}
// 接收返回过来的数据
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
if (obj.success) {
obj.success(xhr.responseText);
}
} else {
if (obj.error) {
obj.error(xhr.status);
}
}
}
}
}
// 接下来我们使用Mock来截取Ajax请求
Mock.mock(/getStudent/, 'get', function () {
return data.data;
});
</script>
</body>

</html>

猜你喜欢

转载自www.cnblogs.com/lyl-0667/p/11286751.html