构造函数封装AJAX
jQuery写一个构造函数,用来调用ajax方法
/*
* type 请求的方式 默认为get
* url 发送请求的地址
* param 发送请求的参数
* ifNeedSign 是否需要登录 默认为false
* dataType 返回JSON数据 默认为JSON格式数据
* callBack 请求的回调函数
*/
(function () {
function AjaxRequest(opts) {
this.type = opts.type || "get";
this.url = opts.url;
this.param = opts.param || {
};
this.ifNeedSign = opts.ifNeedSign || false;
this.dataType = opts.dataType || "json";
this.callBack = opts.callBack;
this.init();
}
AjaxRequest.prototype = {
//初始化
init: function () {
if(this.ifNeedSign) {
let userInfo = JSON.parse(localStorage.getItem('userInfo'))
if(!userInfo) {
console.log("未登录!")
window.location.href = "";
return false;
}
}
this.sendRequest();
},
//发送请求
sendRequest: function () {
var self = this;
let userInfo = JSON.parse(localStorage.getItem('userInfo'))
this.param.user_id = userInfo? userInfo.user_id:''
$.ajax({
type: this.type,
url: this.url,
data: this.param,
dataType: this.dataType,
success: function (res) {
if (res != null && res != "") {
if (self.callBack) {
if (Object.prototype.toString.call(self.callBack) === "[object Function]") {
//Object.prototype.toString.call方法--精确判断对象的类型
self.callBack(res);
} else {
console.log("callBack is not a function");
}
}
}
},
complete: function () {
}
});
}
};
//AjaxRequest函数暴露出全局
window.AjaxRequest = AjaxRequest;
})();
调用方法
new AjaxRequest({
type: "get",//请求类型
url: url,//请求地址
param: {
},//参数
callBack: (res) => {
}//回调
})