1. 程式人生 > >微信小程式通過api介面將json資料展現到小程式示例

微信小程式通過api介面將json資料展現到小程式示例

實現知乎客戶端的一個重要知識前提就是,要知道怎麼通過知乎新聞的介面,來把資料展示到微信小程式端上。 

那麼我們這一就先學習一下,如何將介面獲取到的資料展示到微信小程式上。 

1.用到的知識點

<1> wx.request 請求介面資源(微信小程式api中的發起請求部分) 

<2>swiper 實現輪播圖的元件 

<3>wx:for 迴圈語句 

<4>微信小程式的基礎知識

2.實現原理

首先,先看一下這個請求函式

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

wx.request({

url: '******', //這裡填寫你的介面路徑

header: { //這裡寫你藉口返回的資料是什麼型別,這裡就體現了微信小程式的強大,直接給你解析資料,再也不用去尋找各種方法去解析json,xml等資料了

'Content-Type': 'application/json'

},

data: {//這裡寫你要請求的引數

x: '' ,

y: ''

},

success: function(res) {

//這裡就是請求成功後,進行一些函式操作

console.log(res.data)

}

})

3.程式碼 

分解圖 

<1>首先上一段知乎介面資料的json格式中的開頭

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

"date":"20161114",

"stories":[

{

"images":[

],

"type":0,

"id":8975316,

"ga_prefix":"111422",

"title":"小事 · 我和你們一樣"

},

{

"images":[

],

"type":0,

"id":8977438,

"ga_prefix":"111421",

"title":"成長嘛,誰說就意味著一定要長大了?"

},

<2>index.js中

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

Page({

data: {

duration: 2000,

indicatorDots: true,

autoplay: true,

interval: 3000,

loading: false,

plain: false

},

onLoad: function () {

var that = this//不要漏了這句,很重要

wx.request({

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中

?

1

2

3

4

5

6

7

8

9

10

11

12

<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>

看完這個程式碼,你會想,根據微信小程式的繫結原理,這裡邊的程式碼哪裡呼叫了onLoad()這個函式,不用多想,微信小程式給你省略了這些步驟。直接呼叫zhihu這個陣列就行。