小程序:数据接口封装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 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步