仿jq ajax封装支付宝小程序request.js
/**
* 仿jq ajax
* by练涛 2021.1.20
* @param {*} obj
*/
const myajax = (obj = { url, headers, timeout, method, dataType, data, success, fail, complete }) => {
//入参类型检测,如果不符合预期则,抛出异常
if (typeof obj.url != "undefined" && typeof obj.url != \'string\') throw new TypeError(\'url不是string类型\');
if (typeof obj.headers != "undefined" && typeof obj.headers != "object") throw new TypeError(\'headers不是object类型\');
if (typeof obj.timeout != "undefined" && typeof obj.timeout != \'number\') throw new TypeError(\'timeout不是number类型\');
if (typeof obj.method != "undefined" && typeof obj.method != \'string\') throw new TypeError(\'method不是nstring类型\');
if (typeof obj.dataType != "undefined" && typeof obj.dataType != \'string\') throw new TypeError(\'dataType不是string类型\');
if (typeof obj.data != "undefined" && typeof obj.data != \'object\' && !ArrayBuffer.isView(obj.data)) throw new TypeError(\'data不是object类型或者ArrayBuffer\');
if (typeof obj.success != "undefined" && typeof obj.success != \'function\') throw new TypeError(\'success不是function类型\');
if (typeof obj.fail != "undefined" && typeof obj.fail != \'function\') throw new TypeError(\'fail不是function类型\');
if (typeof obj.complete != "undefined" && typeof obj.complete != \'function\') throw new TypeError(\'complete不是function类型\');
return new Promise((resolve, reject) => {
my.request({
url: devUrl + obj.url, //不会有人不写url吧。。。url!=""
method: obj.method || \'GET\', //默认get
dataType: obj.dataType || \'json\', //默认json
headers: obj.headers || null,
timeout: obj.timeout || 30000, //默认30000
data: obj.data || null,
success: (res) => {
if (typeof obj.success == \'function\') {
obj.success(res);
}
},
// 当程序出错或是网络请求失败都会执行该方法
fail: (res) => {
reject(res);
if (typeof obj.fail == \'function\') {
obj.fail(res);
}
},
complete: function (res) {
//调用结束的回调函数(调用成功、失败都会执行)。
if (typeof obj.complete == \'function\') {
obj.complete(res);
}
}
});
})
}
使用实例
//使用封装好的myajax
/** 参数列表:
* url:必填,其余可选
* headers:{}, timeout, method, dataType,
* data:{},
* success, fail, error, complete
**/
api.myajax({
//url: "/test",
url: "/findUserById",
method: "GET",
headers: {
\'content-type\': \'application/json\'
//设置请求的 HTTP 头对象,默认 {\'content-type\': \'application/json\'},
//该对象里面的 key 和 value 必须是 String 类型。
},
dataType: "json", // text , json , base64
data: {
"id": "2"
},
success: function (res) {
console.log("success:", res);
console.log("data:", res.data);
//this.msg = res.data.data.name
that.setData({
//赋值
msg: res.data.data.name
});
},
fail: function (res) {
console.log("fail:", res);
console.log("fail:", res.data);
}
});
版权声明:本文为famine原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。