之前写过一个封装,只是最基础的。此次在此基础上,增加了请求方式(POST还是GET),等待框,参数
废话少说,上代码
1,js类
/**
* 网络请求的封装
*
* isShow:是否显示加载框 true还是false
* title:加载框的 内容
* url:请求的地址
* params:参数体,如果没有就用{}
* requestType:POST 还是GET
* success:成功的返回
*/
function getData(isShow, title, url, params, requestType, success) {
if (isShow) {
if (title === "" || title === null) {
title = '正在加载...';
}
wx.showLoading({
title: title,
mask: true
})
}
wx.request({
url: url,
data: params,
header: { //根据get或者post来判断使用哪个
'content-type': requestType === 'POST' ?
'application/x-www-form-urlencoded' : 'application/json'
},
method: requestType, //get还是post
success: (res) => {
if (res.data.status == 0) { //根据自己后台的返回,这里是0
wx.hideLoading() //加载框消失
success(res.data) //解析的数据
}
}
})
}
module.exports = {
getData: getData, //网络请求封装
...
}
2,使用
var params = new Object(); //定义一个params
params.homeId = e.detail.current;
utils.getData(false,"",app.globalData.urls + app.globalData.gethomefenxiang, params, "GET", this.getbannerid);
getbannerid: function(res) {
var sharePic = [];
sharePic.push({
id: res.data.id,
shareTitle: res.data.shareTitle,
sharePicSrc: app.globalData.picurls + res.data.picture,
})
this.setData({ //获取数据成功后的数据绑定
sharePic: sharePic,
});
},
ok,如果有更好的方法可以分享一下。