在javascript标签内调用插件
let Service = new Services();
Service.postExample({a:1,b:2},function(data){},function(err){})
//第一个参数为对象,接口需要传的参数
//第二个参数是成功的回调函数(data即为接口返回的数据)
//第三个接口请求失败的回调函数
//封装的js插件代码如下
var Services= function () {
};
Services.prototype = {
postExample: function (data, fn, errFn) {
ajax.post({
url: "请求地址",
data: data,
success: fn,
error: errFn
});
},
getExample: function (data, fn, errFn) {
ajax.get({
url: "请求地址",
data: data,
success: fn,
error: errFn
});
}
}
var ajax = {
//标准 ajax get 方法
get: function (options) {
return $.ajax({
type: 'GET',
url: options.url,
data: options.data,
dataType: 'json',
context: $('body'),
crossDomain: true,
xhrFields: {
withCredentials: true
},
traditional: options.traditional ? options.traditional : false,
async: options.async != false,
success: function (res, fn, errFn) {
if (res.code == 0) { //服务端接口请求成功的状态编码判断
if (options.success) options.success(res);
} else {
toast.show(res.msg) //接口请求成功的业务错误判断,toast提示(见上一篇博客)
}
},
error: function (xhr, type) {
if (options.error != null) {
options.error(xhr);
} else {
toast.show('获取数据失败')
}
}
})
},
//标准 ajax post 方法
post: function (options) {
$.ajax({
type: 'POST',
url: options.url,
data: options.data,
dataType: 'json',
context: $('body'),
crossDomain: true,
xhrFields: {
withCredentials: true
},
//当传文件类型给接口时候,需要设置contentType:false,processDataL:fasle
contentType: (options.contentType !== "" && options.contentType !== undefined) ? options.contentType : "application/x-www-form-urlencoded",
processData: (options.processData !== "" && options.processData !== undefined) ? options.processData : true,
traditional: options.traditional ? options.traditional : false,
success: function (res, fn, errFn) {
if (res.code == 0) {
if (options.success) options.success(res);
} else {
if (options.error != null) {
options.error(res);
} else {
toast.show(res.msg)
}
}
},
error: function (xhr, type) {
if (options.error != null) {
options.error(xhr);
} else {
toast.show('获取数据失败')
}
}
})
}
};