不去做怎么知道做不到,用心做好每一天做好每一件事。|

轻风细雨_林木木

园龄:6年3个月粉丝:4关注:1

小程序:数据接口封装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 }, () => {}) // 赋值回调函数
}

本文作者:轻风细雨_林木木

本文链接:https://www.cnblogs.com/linzhifen5/p/16961161.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   轻风细雨_林木木  阅读(101)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 尚好的青春 孙燕姿
  2. 2 孙燕姿
  3. 3 克卜勒 孙燕姿
克卜勒 - 孙燕姿
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.