//app.js
App({
/**
* @name 请求数据
* @param {string} url 请求地址
* @param {object} params 参数
* @param {function} callback 成功回调函数
* @param {function} failcall 失败回调函数
* @param {bool} loading 是否显示加载框
*/
ajax: function(url, params, callback, failcall, loading) {
// 判断是否需要显示加载框
if (!loading) {
wx.showLoading({
title: '加载中',
mask: true
});
}
wx.request({
url: 'http://www.baidu.com' + url,
data: params,
header: {
'content-type': 'application/x-www-form-urlencoded;'
},
method: "POST",
success: function(res) {
wx.hideLoading();
// 此处与接口约定好,返回的code对应不同的结果,0 代表请求成功 300 需要跳转,返回跳转链接forward 500 为请求异常,返回错误信息message
if (res.data.code == 0) {
// 如果有请求成功回调函数,则调用
typeof callback == "function" && callback(res.data);
} else if (res.data.code == 300) {
if (res.data.forward) {
wx.navigateTo({
url: res.data.forward
})
}
} else {
// 如果有请求失败回调函数,则调用
if (failcall) {
failcall(res.data);
} else {
if (res.data.message) {
wx.showModal({
title: '提示',
content: res.data.message,
showCancel: false,
confirmColor: '#92BA00'
});
}
}
}
},
fail: function(res) {
console.log(res);
wx.hideLoading();
wx.showModal({
title: '提示',
content: "网络异常,请稍后再试",
showCancel: false,
confirmColor: '#92BA00'
});
return false;
}
});
},
/**
* @name 请求数据
* @param {string} url 请求地址
* @param {object} params 参数
* @param {string} forward 登录后跳转链接
* @param {function} callback 成功回调函数
* @param {function} failcall 失败回调函数
* @param {bool} loading 是否显示加载框
*/
ajax_user: function(url, params, forward, callback, failcall, loading) {
var app = this;
var userId = wx.getStorageSync('userId');
// 判断用户是否登录,未登录先进行登录操作
if (userId == '') {
wx.login({
success: function(res) {
if (res.code) {
var code = res.code;
// 进行登录操作
app.ajax('/users/login', {
lat: app.latitude,
lng: app.longitude,
code: code
}, function(data) {
// 登录成功,将user_id存储到本地
var userId = data.user_id;
wx.setStorageSync("userId", userId);
// 判断是否需要跳转到指定页面,forward不为空则跳转,为空则继续之前请求
if (forward != '') {
wx.navigateTo({
url: forward
});
} else {
params.user_id = userId;
app.ajax(url, params, callback, failcall, loading);
}
});
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
}
});
} else {
// 已登录直接请求
params.user_id = userId;
app.ajax(url, params, callback, failcall, loading);
}
}
})
微信小程序wx.request接口封装
最新推荐文章于 2025-06-23 17:27:52 发布