wx.request就是ajax,與后臺交互請求數(shù)據(jù),基礎(chǔ)參數(shù)和用法與jQuery的$.ajax方法類似。下面是官方文檔對wx.request基礎(chǔ)參數(shù)的說明:(圖片一上傳就模糊了,看不清楚 點(diǎn)擊這里 )
url和data用過$.ajax的都知道,url是你從后臺獲取數(shù)據(jù)的接口連接,data是你需要發(fā)送過去的數(shù)據(jù),下面的案例也有說明;
header的默認(rèn)是 ‘content-type’: ‘application/json’對數(shù)據(jù)進(jìn)行 JSON 序列化,’application/x-www-form-urlencoded’是將數(shù)據(jù)轉(zhuǎn)換成 query string ;
其他的沒有什么好說明的,上面文檔已經(jīng)說明的很詳細(xì)了。
下面我介紹一下怎么獲取openId和sessionKey:
App({
onLaunch: function() {
wx.login({ //微信登錄
success: function(res) { //登錄成功后執(zhí)行的的函數(shù)
//發(fā)送 res.code 到后臺換取 openId, sessionKey
if (res.code) {
//發(fā)起網(wǎng)絡(luò)請求
wx.request({
url: 'https://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('獲取用戶登錄態(tài)失敗!' + res.errMsg)
}
}
});
}
})