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