小程序:数据接口封装get、post
GET和POS封装:
/**
* GET请求
* url:接口
* doSuccess:成功的回调函数
* doFail:失败的回调函数
* dataNam 赋值变量的名称
* getData 传参值
* cache 缓存值名
* _this this对象
* hidLoading 现实loding
*/
function getData(url, doSuccess, dataNam, getData, _this, hidLoading) {
var token = wx.getStorageSync('token') //重新刷新token
if(!hidLoading){
wx.showLoading({
title: "加载中...",
mask: true
})
}
requestTimes++
wx.request({
url: host + url,
header: {
// "content-type": "application/json; charset=UTF-8",
"token": token
},
data: getData,
method: 'GET',
success: function (res) {
if(res.data.code === 200){
doSuccess(res.data.data, dataNam, _this); // 成功函数
}else if(res.statusCode === 200){ // 获取部门返回值错误做特殊处理
doSuccess(res.data, dataNam, _this);
}else{
console.log('数据调用成功,但返回值错误')
}
},
fail: function () {
console.log('数据调用失败')
},
complete:()=>{
requestTimes--
if(requestTimes === 0 && !hidLoading) {
wx.hideLoading()
}
}
})
}
/**
* POST请求
* url:接口
* postData:参数,json类型
* doSuccess:成功的回调函数
* dataNam 赋值变量的名称
*/
function request(url, postData, doSuccess, dataNam) {
var token = wx.getStorageSync('token') //重新刷新token
wx.showLoading({
title: "加载中...",
mask: true
})
requestTimes++
wx.request({
url: host + url,
header: {
// "content-type": "application/x-www-form-urlencoded",
"token": token
},
data: postData,
method: 'POST',
success: function (res) {
if(res.data.code === 200){
doSuccess(res.data.data, dataNam); // 成功函数
}else{
console.log('数据调用成功,但返回值错误')
}
},
fail: function () {
console.log('数据调用失败')
},
complete:()=>{
requestTimes--
if(requestTimes === 0) {
wx.hideLoading()
}
}
})
}
调用和赋值:
// 调用接口函数
call.getData(butApi, this.shuffleSuc, 'butList', this.data.butUpdata);
/**
* 赋值函数:
* data 接口调用成功返回值
* dataName 赋值到wxml的值名
*/
shuffleSuc: function (data, dataNam) {
this.setData({ [dataNam]: data }, () => {}) // 赋值回调函数
}

浙公网安备 33010602011771号