今天小編給大家分享一下怎么通過api接口將json數據展現到小程序中的相關知識點,內容詳細,邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。
如何將接口獲取到的數據展示到微信小程序上。
1.用到的知識點
<1> wx.request 請求接口資源(微信小程序api中的發起請求部分)
<2>swiper 實現輪播圖的組件
<3>wx:for 循環語句
<4>微信小程序的基礎知識
2.實現原理
首先,先看一下這個請求函數
wx.request({
url: '******', //這里填寫你的接口路徑
header: { //這里寫你借口返回的數據是什么類型,這里就體現了微信小程序的強大,直接給你解析數據,再也不用去尋找各種方法去解析json,xml等數據了
'Content-Type': 'application/json'
},
data: {//這里寫你要請求的參數
x: '' ,
y: ''
},
success: function(res) {
//這里就是請求成功后,進行一些函數操作
console.log(res.data)
}
})3.代碼
分解圖

<1>首先上一段知乎接口數據的json格式中的開頭
"date":"20161114",
"stories":[
{
"images":[
"http://jb51.net.com/76125c357aa7b0ca6c9cbc41b4a5326d.jpg"
],
"type":0,
"id":8975316,
"ga_prefix":"111422",
"title":"小事 · 我和你們一樣"
},
{
"images":[
"http://jb51.net/7c908a5940384123fd88287dbc6a2c98.jpg"
],
"type":0,
"id":8977438,
"ga_prefix":"111421",
"title":"成長嘛,誰說就意味著一定要長大了?"
},<2>index.js中
Page({
data: {
duration: 2000,
indicatorDots: true,
autoplay: true,
interval: 3000,
loading: false,
plain: false
},
onLoad: function () {
var that = this//不要漏了這句,很重要
wx.request({
url: 'http://news-at.zhihu.com/api/4/news/latest',
headers: {
'Content-Type': 'application/json'
},
success: function (res) {
//將獲取到的json數據,存在名字叫zhihu的這個數組中
that.setData({
zhihu: res.data.stories,
//res代表success函數的事件對,data是固定的,stories是是上面json數據中stories
})
}
})
}
})<3> index.wxml中
<view >
<swiper indicator-dots="{{indicatorDots}}"
autoplay="{{autoplay}}" class="banners" interval="{{interval}}" duration="{{duration}}">//這里邊的屬性不重要,看下邊
<block wx:for="{{zhihu}}">
<swiper-item class="banner" >
<image src="{{item.image}}" data-id="{{item.b}}" bindtap="bindViewTap" class="banner-image" width="100%" height="100%"/>
<text class="banner-title">{{item.title}}</text>
</swiper-item>
</block>
</swiper>
</view>以上就是“怎么通過api接口將json數據展現到小程序中”這篇文章的所有內容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學習更多的知識,請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。