微信小程序wx.request的回调使用

微信小程序调用外部js中的wx.request方法时,因为异步的请求机制,我们不能在其success:function()中直接返回需要的数据。

例子:

一:

//此方法处于外部文件 “utils/util.js” 中进行了定义function request_method(url, callback){ wx.request({ url: url, method: ‘GET‘, header: { ‘Content-Type‘: ‘application/json‘ }, success: function (res) { callback && callback(res.data); } });}

//需要加上这段来暴露你定义的方法,否则在外部找不到
module.exports = {
request_method:request_method
}
 

二 当前页面对应 js方法的:

微信小程序wx.request的回调使用
//首先要引入公共jsvar util = require(‘../../utils/util.js‘);util.request_method(url, (res) => { this.setData({ otherData: res });});

 

相关文章