小程序登录异步请求获openid在页面onload之后执行的简单解决办法!

app.js里面增加一个全局方法:
//登录,设置参数,可传入一个函数

userLogin: function (fn) {
        var _this = this;
        wx.login({
          success: res => {
            if (res.code) {
              //先判断是否已存在openid,没有的话才请求兑换
              if (_this.globalData.userOpenId=='')
              {
                wx.request({
                  url: 'https://你的网址?code=' + res.code,
                  header: {
                    'content-type': 'application/json'
                  },
                  success: function (res) {
                  //兑换成功后将openid存入全局变量userOpenId 
                    _this.globalData.userOpenId = res.data;
                    //执行传入的函数参数,相当于回调函数
                    return fn();
                  }
                });
              }
              else
              {
              //已经存在openid的话也执行传入的函数参数
                return fn();
              }
            }
            else
            {
              return;
            }
          }
        });
  },
  globalData: {
    userOpenId: ''
  }

然后在相应的page页面调用

getApp().userLogin(function(){

    //页面的onload请求写在这里
      wx.request({
        url: 'https://你的网址?openid=' + getApp().globalData.userOpenId,
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
        //....
        }

});

你可能感兴趣的:(小程序登录异步请求获openid在页面onload之后执行的简单解决办法!)