之前在学习JS高级的时候,为了锻炼面向对象的思想,采用面向对象的方式对AJAX进行了封装。
//对数据进行处理
function objToString(obj){
const arr=[]
for(const key in obj){
arr.push(`${key}=${obj[key]}`)
}
return arr.join('&')
}
function ajax(obj) {
//初始化数据
this.url = obj.url;
this.method = (obj.method || "get").toLowerCase();
this.data = JSON.stringify(obj.data) || JSON.stringify({});
//创建xhr对象
this.xhr = new XMLHttpRequest();
//对请求方式进行判断
if (this.method == "get") {
this.get();
} else {
this.post();
}}
//原型上添加get方法
ajax.prototype.get = function () {
this.xhr.open("get", this.url + "?" + objToString(this.data), true);
this.xhr.send();
};
//原型上添加post方法
ajax.prototype.post = function () {
this.xhr.open("post", this.url,true);
//设置请求头
this.xhr.setRequestHeader(
"content-type",
"application/x-www-form-urlencoded"
);
//发送请求
this.xhr.send(this.data);
};
//原型上添加成功的回调函数
ajax.prototype.success=function(res){
this.xhr.onreadystatechange = function () {
//判断返回状态
if (this.readyState == 4 && this.status == 200) {
//将返回的信息转为JSON格式
res(JSON.parse(this.responseText));
}
console.log(res);
}}