小程序wx.request接口封装
//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); } } })
相关推荐
-
js计算器 javascript
2019-1-7
-
压缩上传图片 javascript
2019-1-7
-
SVG 动态添加元素与事件 javascript
2019-1-7
-
canvas旋转图片 javascript
2019-1-7
-
js浮点数加减乘除 javascript
2019-1-8
-
小程序wx.request接口封装 javascript
2019-1-8
-
点击空白处关闭弹窗 [ JavaScript ] javascript
2019-1-7
-
js跳转页面的方法 javascript
2019-1-7
-
canvas 视频音乐播放器 核心 javascript
2019-1-8
-
发送验证码定时器 javascript
2019-1-8