我封装在了app.js文件下,以便于其它页面js调用
/**
* 发起请求
* @param r_url 请求地址
* @param r_data 参数 {string/object/Array}
* @param r_method 方法 默认为GET {GET、POST}
* @param isLoad 是否显示加载框 默认不显示
* @param r_dataType 响应数据 默认json
*/
wxRequest: function (r_url, params = {}, r_method = 'GET', isLoad = true)
{
var _this = this;
let promise = new Promise(function (resolve, reject) {
if (isLoad === true) {
wx.showLoading({ title: '正在获取' });
}
wx.request({
url: _this.globalData.requestUrl + r_url,
data: params,
method: r_method,
header: {
"content-type": r_method == 'GET' ? 'application/json' : 'application/x-www-form-urlencoded'
},
timeout: 3000,
success: function (res) {
if (isLoad === true) {
wx.hideLoading()
}
//请求成功
resolve(res.data);
},
fail: function (err) {
if (isLoad === true) {
wx.hideLoading()
}
_this.showAlert('当前网络不佳');
reject(err)
}
})
})
return promise;
},
showAlert是我自己封装的一个弹窗(也在app.js),wx.showToast 改造的,代码如下
/**
* 弹窗提示
* @param {String} str 提示语句
* @param icon 弹窗图标 默认为不显示 success、loading
*/
showAlert: function (str = 'Msg', icon = 'none', durationTime = 1500)
{
var alert = wx.showToast({
title: str,
icon: icon,
duration: durationTime,
mask: true
});
return alert;
},
调用:
// 获取应用实例
const app = getApp()
// 发起请求
app.wxRequest('/index/index').then(
res => {
// 获取接口参数
console.log(res)
}
)
不定期更新,喜欢就关注我吧!