Ajax-jQuery封装
在经过博主前几篇的文章过来之后,本文首先将介绍一下使用 jQuery 当中的 Ajax,说明,在看本文的 jquery 当中的 Ajax 需要导入 jQuery,官方文档地址:https://jquery.cuishifeng.cn/index.html
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jquery-ajax</title>
<script src="../js/jquery-1.12.4.js"></script>
<script>
window.onload = () => {
let oBtn = document.querySelector("button");
oBtn.onclick = () => {
$.ajax({
url: "ajax-jquery.php",
type: "get",
data: "userName=BNTang&userPwd=654321",
success: (msg) => {
alert(msg);
},
error: (xhr) => {
alert(xhr.status);
}
});
}
}
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>
如上代码的特点,就是属性当中的位置可以任意改变,type 属性当中的 get 与 post 可以大小写都可以进行请求,看了如上 jQuery 当中的 ajax 方法之后然后我们再来看看我们自己封装的 ajax 试着与 jQuery 当中的 ajax 的特点去试着发送请求看一下,导入我们自己的 ajax 方法:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jquery-ajax</title>
<script src="myAjax.js"></script>
<script>
window.onload = () => {
let oBtn = document.querySelector("button");
oBtn.onclick = () => {
ajax("get", "ajax-jquery.php", {
"userName": "BNTang",
"userPwd": "123456"
}, 3000, (msg) => {
alert(msg.responseText);
}, (xhr) => {
alert(xhr.status);
}
);
}
}
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>
很显然是不可以的,那么我们这个时候就需要在完善一下我们自己封装 ajax 代码了,完善的要与 jQuery 当中的特点一致的话其实就只需要抽取一个对象来进行接收参数即可:
const obj2str = (data) => {
data = data || {};
data.t = new Date().getTime();
let res = [];
for (let key in data) {
// 在URL中是不可以出现中文的, 如果出现了中文需要转码
// 可以调用encodeURIComponent方法
// URL中只可以出现字母/数字/下划线/ASCII码
res.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
}
return res.join("&");
}
const ajax = (option) => {
// 0.将对象转换为字符串
// key=value&key=value;
let str = obj2str(option.data);
// 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 (option.type.toLowerCase() === "get") {
xmlHttp.open(option.type, option.url + "?" + str, true);
// 3.发送请求
xmlHttp.send();
} else {
xmlHttp.open(option.type, option.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("接收到服务器返回的数据");
option.success(xmlHttp);
} else {
// console.log("没有接收到服务器返回的数据");
option.error(xmlHttp);
}
}
}
// 判断外界是否传入了超时时间
if (option.timeout) {
timer = setInterval(() => {
console.log("中断请求");
xmlHttp.abort();
clearInterval(timer);
}, option.timeout);
}
}
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jquery-ajax</title>
<script src="myAjax.js"></script>
<script>
window.onload = () => {
let oBtn = document.querySelector("button");
oBtn.onclick = () => {
ajax({
type: "post",
url: "ajax-jquery.php",
data:{
"userName": "BNTang",
"userPwd": "123456"
},
timeout: 3000,
success: (msg) => {
alert(msg.responseText);
},
error: (xhr) => {
alert(xhr.status);
}
});
}
}
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具