在入口處的 app.js 中定義了一個獲取用戶 OpenId 的函數,在微信的登陸接口 wx.login 中發起網絡請求。這個函數傳入一個回調函數 cbjavascript
getOpenIdData: function(cb) { var that = this //調用登陸接口 wx.login({ success: function(res) { wx.request({ url: 'https://api.weixin.qq.com/sns/jscode2session', data: { appid: "wx6224eb*********", secret: "879b58fc64bc5**************", js_code: res.code, grant_type: "authorization_code" }, success: function(res) { // 保存到全局變量中 that.globalData.openid = res["data"]["openid"] cb(that.globalData.openid) }, fail: function() { console.log("request error") } }) } }) }
在 index.js 文件時,使用 getOpenIdData 接口java
var app = getApp() app.getOpenIdData(function(openid){ //回調更新數據 that.setData({ openid: openid }) })
在接口中傳入匿名函數api
function(openid){ //回調更新數據 that.setData({ openid: openid }) }
先將匿名函數傳入到 app.js 中,獲取到 openid 數據。再回到 index.js 將數據賦給此文件的全局變量。這樣就實現跨文件傳遞數據。微信