Constructor encapsulates AJAX
jQuery writes a constructor to call the ajax method
(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]") {
self.callBack(res);
} else {
console.log("callBack is not a function");
}
}
}
},
complete: function () {
}
});
}
};
window.AjaxRequest = AjaxRequest;
})();
Call method
new AjaxRequest({
type: "get",
url: url,
param: {
},
callBack: (res) => {
}
})