實現(xiàn)知乎客戶端的一個重要知識前提就是,要知道怎么通過知乎新聞的接口,來把數(shù)據(jù)展示到微信小程序端上。
那么我們這一就先學習一下,如何將接口獲取到的數(shù)據(jù)展示到微信小程序上。
1.用到的知識點
<1> wx.request 請求接口資源(微信小程序api中的發(fā)起請求部分)
<2>swiper 實現(xiàn)輪播圖的組件
<3>wx:for 循環(huán)語句
<4>微信小程序的基礎知識
2.實現(xiàn)原理
首先,先看一下這個請求函數(shù)
wx.request({ url: '******', //這里填寫你的接口路徑 header: { //這里寫你借口返回的數(shù)據(jù)是什么類型,這里就體現(xiàn)了微信小程序的強大,直接給你解析數(shù)據(jù),再也不用去尋找各種方法去解析json,xml等數(shù)據(jù)了 'Content-Type': 'application/json' }, data: {//這里寫你要請求的參數(shù) x: '' , y: '' }, success: function(res) { //這里就是請求成功后,進行一些函數(shù)操作 console.log(res.data) }})
3.代碼
分解圖
<1>首先上一段知乎接口數(shù)據(jù)的json格式中的開頭
"date":"20161114", "stories":[ { "images":[ "http://VeVB.COm.com/76125c357aa7b0ca6c9cbc41b4a5326d.jpg" ], "type":0, "id":8975316, "ga_prefix":"111422", "title":"小事 ? 我和你們一樣" }, { "images":[ "http://VeVB.COm/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數(shù)據(jù),存在名字叫zhihu的這個數(shù)組中 that.setData({ zhihu: res.data.stories, //res代表success函數(shù)的事件對,data是固定的,stories是是上面json數(shù)據(jù)中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>
看完這個代碼,你會想,根據(jù)微信小程序的綁定原理,這里邊的代碼哪里調(diào)用了onLoad()這個函數(shù),不用多想,微信小程序給你省略了這些步驟。直接調(diào)用zhihu這個數(shù)組就行。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答