微信小程序通過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>

看完這個代碼,你會想,根據微信小程序的綁定原理,這里邊的代碼哪里調用了onLoad()這個函數,不用多想,微信小程序給你省略了這些步驟。直接調用zhihu這個數組就行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM