// 自定义网络请求方法
var common = {}
var baseUrl = "" //默认请求地址前缀
/*
url 请求地址
param 请求参数
callFun 请求成功回调
that 防止页面this指向问题
errCallBack 请求失败回调
hideLoading 是否隐藏加载弹框 默认展示
methods 设置请求方式Get请求或是Post请求
*/
common.post = function(url, param, callFun, that, errCallBack, hideLoading,methods) {
if (!hideLoading) {
wx.showToast({
title: '加载中',
icon: 'loading',
mask:true,
duration:500
})
}
let postUrl = baseUrl + url
if(param){
if(methods && methods=="Get"){
if (typeof param == 'object') {
for (let key in param) {
postUrl += '&' + key + '=' + param[key];
};
param = null;
}
}
}else if(!param){
param = {}
}
return new Promise((resolve, reject) => {
wx.request({
url: postUrl,
method: methods || 'Post',
data: param || {},
success: res => {
resolve(res)
if(typeof callFun==='function'){
callFun(res.data)
}else if(typeof that[callFun]==='function'){
that[callFun](res.data)
}else if(typeof that[callFun]==='undefined'){
console.log("未定义方法:"+callFun)
}
if (!hideLoading) {
wx.hideToast()
}
},
fail: err => {
reject(err)
if (errCallBack) {
if(typeof(errCallBack)==='function'){
errCallBack(err)
}else if(typeof that[errCallBack] === 'function'){
that[errCallBack](err)
}else if(typeof that[errCallBack] === 'undefined'){
// console.error('未定义方法:'+errCallBack)
}
}
if (!hideLoading) {
wx.hideToast()
}
}
});
}).then((res)=>{
console.log(postUrl,res.data) //打印接口数据方便调试
}).catch((err)=>{
console.log("请求接口出错",err)
})
}
common.get = function(url, param, callFun, that, errCallBack, hideLoading) {
common.post(url, param, callFun, that, errCallBack, hideLoading,'Get')
}
module.exports = common
使用时先在页面引入该js,然后在需要的时候调用,例如:
var common=require('../../utils/common.js')
Page({
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let that=this
common.post("a.php",{name:'abc',id:1},'resData',that,'errData')
},
resData(res){
console.log(res)
},
})
注: 根据实际情况修改使用!