/*
type 请求的方式 默认为get
url 发送请求的地址
param 发送请求的参数
isShowLoader 是否显示loader动画 默认为false
dataType 返回JSON数据 默认为JSON格式数据
callBack 请求的回调函数
contentType 发送信息至服务器时内容编码类型;默认为表单提交的方式;当提交二进制数据时,为false
processData 配合表单方式就是true;contentType为false,则为false;
traditional 当传递数组时,必须为true;否则后台无法接到参数
*/
/*
* 调用示例
* new PostTo({
type: "POST",
url: "https://minih.com/find",
param: {
token: 'mu_2389f129-463d-4955-88c2-4a701c69a310',
partnerId: 88888,
st: 1 //页码
},
dataType: "JSON",
callBack: function (res) {
console.log(res);
}
});
*/
(function () {
function PostTo(opts) {
this.type = opts.type || "POST";
this.url = opts.url;
this.param = opts.param || {};
//this.isShowLoader = opts.isShowLoader || false;
this.isBtnActive =
typeof(opts.isBtnActive) == 'undefined' ?
true : opts.isBtnActive;
this.dataType = opts.dataType || "JSON";
this.traditional = opts.traditional || false;
this.callBack = opts.callBack;
this.contentType =
typeof(opts.contentType) == 'undefined'?
"application/x-www-form-urlencoded;charset=UTF-8":opts.contentType;
this.processData =
typeof(opts.contentType) == 'undefined'?
true:opts.contentType;
this.init();
}
PostTo.prototype = {
//初始化
init: function () {
this.initToastr();
this.sendRequest();
},
//初始化toastr的配置
initToastr:function(){
toastr.options = {
closeButton: false,
debug: false,
progressBar: false,
positionClass: "toast-center-center",
onclick: null,
showDuration: "200",
hideDuration: "200",
timeOut: "1500",
extendedTimeOut: "300",
showEasing: "swing",
hideEasing: "linear",
showMethod: "fadeIn",
hideMethod: "fadeOut"
};
},
//使相应的提交按钮不可用
btnDisabled: function(){
if(this.isBtnActive){
//console.log($(".btnLoader"));
$(".btnLoader").prop("disabled",true);
//$(".btnLoader").attr({"disabled":"disabled"});
}
},
btnAbled:function(){
if(this.isBtnActive){
$(".btnLoader").prop("disabled",false);
//$(".btnLoader").removeAttr("disabled");
}
},
//发送请求
sendRequest: function () {
var self = this;
$.ajax({
type: this.type,
url: this.url,
data: this.param,
contentType: this.contentType,
processData: this.processData,
traditional: this.traditional,
dataType: this.dataType,
beforeSend: this.btnDisabled(),
success: function (res) {
//self.hideLoader();
self.btnAbled();
if (res != null && res != "" && res.status == 1) {
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");
}
}
}else{
if(!res.msg){
res.msg = "操作失败";
}
//Ewin.alert({ message: res.msg });
toastr.error(res.msg);
}
},
error: function (xhr, type) {
console.log('网络错误')
}
});
}
};
window.PostTo = PostTo;
})();
Jquery中的Ajax再次封装
最新推荐文章于 2022-06-01 20:24:18 发布