最近看了一些微信小程序的教程,在微信小程序中我們用wx.request來請求數(shù)據(jù)。先簡單介紹一下wx.request API,因為獲取openId、sessionKey也需要用這個API。
wx.request就是ajax,與后臺交互請求數(shù)據(jù),基礎參數(shù)和用法與jQuery的$.ajax方法類似。下面是官方文檔對wx.request基礎參數(shù)的說明:(圖片一上傳就模糊了,看不清楚 點擊這里 )
url和data用過$.ajax的都知道,url是你從后臺獲取數(shù)據(jù)的接口連接,data是你需要發(fā)送過去的數(shù)據(jù),下面的案例也有說明;
header的默認是 ‘content-type’: ‘a(chǎn)pplication/json’對數(shù)據(jù)進行 JSON 序列化,’application/x-www-form-urlencoded’是將數(shù)據(jù)轉換成 query string ;
其他的沒有什么好說明的,上面文檔已經(jīng)說明的很詳細了。
下面我介紹一下怎么獲取openId和sessionKey:
App({ onLaunch: function() { wx.login({ //微信登錄 success: function(res) { //登錄成功后執(zhí)行的的函數(shù) //發(fā)送 res.code 到后臺換取 openId, sessionKey if (res.code) { //發(fā)起網(wǎng)絡請求 wx.request({ url: 'http://api.weixin.qq.com/sns/jscode2session',//這是固定的就是這個地址 data: { appid:'AppID',//小程序的ID secret:'AppSecret',//小程序的密鑰 js_code:res.code, grant_type:'authorization_code' }, method: 'POST', header:{ 'content-type': 'application/json' // 默認值 }, success: function(res) { console.log(res.data.openId)//openId console.log(res.data.session_key)//sessionKey }, fail: function(res) { console.log('獲取openId、sessionKey失??!' + res.errMsg) } }) } else { console.log('獲取用戶登錄態(tài)失敗!' + res.errMsg) } } }); } })
小程序的ID和密鑰,可以在微信公眾平臺->設置->開發(fā)設置里查看。
轉載時請注明出處及相應鏈接,本文永久地址:http://blog.it985.com/22705.html
微信打賞
支付寶打賞
感謝您對作者Jonny的打賞,我們會更加努力!如果您想成為作者,請點我