微信小程序開發(fā)中網(wǎng)絡(luò)請求必不可少,今天說說最簡單的請求.后續(xù)會嘗試上傳下載,Socket這些.
1.一個微信小程序,同時只能有5個網(wǎng)絡(luò)請求連接。
這個規(guī)定應(yīng)該是微信為了保證用戶體驗制定的,畢竟是小程序.
2.wx.request(OBJECT) 參數(shù)說明:
微信小程序支持GET,POST等請求.用method可以設(shè)置.
以下是GET請求的代碼:
//rate.js
//獲取應(yīng)用實例
var app = getApp()
Page( {
data: {
code: 'USD',
currencyF_Name: '',
currencyT_Name: '',
currencyF: '',
currencyT: '',
currencyFD: 1,
exchange: 0,
result: 0,
updateTime: '',
},
onLoad: function( options ) {
var that = this;
//獲取匯率
wx.request( {
url: "http://op.juhe.cn/onebox/exchange/currency?key=我的appkey&from=CNY&to="+code,
success: function( res ) {
that.setData( {
currencyF_Name: res.data.result[0].currencyF_Name,
currencyT_Name: res.data.result[0].currencyT_Name,
currencyF: res.data.result[0].currencyF,
currencyT: res.data.result[0].currencyT,
currencyFD: res.data.result[0].currencyFD,
exchange: res.data.result[0].exchange,
result: res.data.result[0].result,
updateTime: res.data.result[0].updateTime,
})
}
})
}
})
上面代碼中只需要給出URL即可,onLoad函數(shù)在頁面初始化時啟動,wx.request({})中success的res.data是從后臺獲取的數(shù)據(jù),這一點需要注意.
以下是獲取的json數(shù)據(jù)的格式.
json的解析都不需要自己做了.我做Android的時候還得用gson或者是fastjson來解析json.
微信為我們解決了很多麻煩.
微信小程序開發(fā)網(wǎng)絡(luò)請求文檔