微信小程序調(diào)用天氣接口并且渲染在頁面過程詳解
前兩天寫了關(guān)于組件庫 iView Weapp的教程,其實(shí)也就是把文檔上的例子拿出來體驗(yàn)了一遍,今天寫一個具體的例子,調(diào)用一個免費(fèi)的天氣接口的api,并且把所獲取的內(nèi)容展示在前端的界面,前端界面與 iView Weapp結(jié)合,展示的一個小的demo.
先上效果
開始寫代碼:
1:找打一個免費(fèi)的天氣接口
免費(fèi)接口api:
https://www.apiopen.top/api.html#top
https://www.apiopen.top/weatherApi?city=%E4%B8%8A%E6%B5%B7
2:寫js代碼
寫一個request請求,把準(zhǔn)備好的天氣接口放在url里面,當(dāng)請求成功的時(shí)候,在控制臺打印一下返回的res.data數(shù)據(jù)
wx.request({ url: 'https://www.apiopen.top/weatherApi?city=%E4%B8%8A%E6%B5%B7', header: { 'content-type': 'application/json' }, success: res => { console.log(res.data) } })
這個時(shí)候可以看到控制臺已經(jīng)有打印了接口數(shù)據(jù)了
3:接收到了數(shù)據(jù)之后,是對數(shù)據(jù)進(jìn)行處理
在請求接口成功之后,用setData接收數(shù)據(jù),并且需在data中聲明一個接收數(shù)據(jù)的變量。
4:js寫完之后,現(xiàn)在開始寫wxml里面的內(nèi)容,將數(shù)據(jù)渲染在界面
前面說用的是組件庫 iView Weapp,樣式可以自己選擇,我這里選了一個卡片。
在使用組件的時(shí)候,需要在json里面引入一下:
https://weapp.iviewui.com/components/card
將里面的代碼復(fù)制過來,放在wxml,并且根據(jù)改成自己需要的。
<view class='list-li mflex' wx:for="{{list.forecast}}" wx:key="index"> <i-card title="{{list.city}}天氣" extra="{{list.city}}" thumb="https://i.loli.net/2017/08/21/599a521472424.jpg"> <view slot="content"> {{item.date}} {{item.high}} {{item.low}} </view> <view slot="footer">{{list.ganmao}}</view> </i-card> </view>
ok,到這里就完成了。
5:貼一下完整的代碼:
json:
{ "usingComponents": { "i-card": "../../dist/card/index" } }
js:
Page({ data: { list: [] }, onLoad: function (options) { wx.request({ url: 'https://www.apiopen.top/weatherApi?city=%E4%B8%8A%E6%B5%B7', header: { 'content-type': 'application/json' }, success: res => { console.log(res.data) this.setData({ //第一個data為固定用法,第二個data是json中的data list: res.data.data }) } }) }, })
wxml:
<view class='list-li mflex' wx:for="{{list.forecast}}" wx:key="index"> <i-card title="{{list.city}}天氣" extra="{{list.city}}" thumb="https://i.loli.net/2017/08/21/599a521472424.jpg"> <view slot="content"> {{item.date}} {{item.high}} {{item.low}} </view> <view slot="footer">{{list.ganmao}}</view> </i-card> </view>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
TypeScript類型系統(tǒng)自定義數(shù)據(jù)類型教程示例
這篇文章主要為大家介紹了TypeScript類型系統(tǒng)自定義數(shù)據(jù)類型教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11JavaScript 定時(shí)器 SetTimeout之定時(shí)刷新窗口和關(guān)閉窗口(代碼超簡單)
這篇文章主要介紹了JavaScript 定時(shí)器 SetTimeout之定時(shí)刷新窗口和關(guān)閉窗口(代碼超簡單)的相關(guān)資料,需要的朋友可以參考下2016-02-02Layui點(diǎn)擊圖片彈框預(yù)覽的實(shí)現(xiàn)方法
今天小編就為大家分享一篇Layui點(diǎn)擊圖片彈框預(yù)覽的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09