微信小程序的(de)ajax數據請求wx.request
發表時(shí)間:2021-3-31
發布人(rén):融晨科技
浏覽次數:102
微信小程序的(de)ajax數據請求,很多同學找不(bù)到(dào)api在(zài)哪個(gè)位置,這(zhè)裏單獨把小程序的(de)ajax請求給列出(chū)來(lái),微信小程序的(de)請求就(jiù)是(shì)wx.request這(zhè)個(gè)api,wx.request(一些對象參數),微信小程序不(bù)同于(yú)浏覽器的(de)ajax請求,可以(yǐ)直接跨域請求不(bù)用考慮跨域問題。
使用小程序官方提供的(de)數據請求api發起數據請求
wx.request(OBJECT)
wx.request發起的(de)是(shì)https請求。一個(gè)微信小程序,同時(shí)隻能有5個(gè)網絡請求連接。
示例代碼:
wx.request({
url: 'test.php',
data: {
x: '' ,
y: ''
},
header: {
'Content-Type': 'application/json'
},
success: function(res) {
console.log(res.data)
}
})
微信小程序中使用fetch做ajax請求
fetch是(shì)一種新的(de)ajax請求規範,經懶人(rén)建站測試,fetch在(zài)小程序中也(yě)是(shì)支持的(de),測試ajax請求代碼如下:
then中帶代碼是(shì)測試,這(zhè)裏是(shì)節選了(le/liǎo)小部分代碼,實際使用需要(yào / yāo)自行修改。
fetch('http://www.51xuediannao.com/json.php?typeid=34&page=1&pagesize=10')
.then(function(response){
if(response.status==200){
that.data.page++;
return response.json();
}
}).then(function(data){
console.log(data);
//更新數據
that.setData({
listArr:that.data.page==1 ? data : that.data.listArr.concat(data)
})
console.log(that.data.listArr);
})