1问题描述

使用小程序使用天气api显示天气。

2算法描述

首先打开微信开发者工具创建一个新的小程序项目,但是可以不选择任何模板,进入新建的小程序,先将index中的js,wxml,wxss中的原有格式删除,保留空白页面。首先在index.js中重新建立page,加入data数据,先是获取城市id,然后再获取数据,以及获取结果,在获取的结果中输入要使用的api的请求示例;使用的是url:’’(请求示例)和key:’’(密钥);注意,要使用的请求示例只是api接口中的一部分。加入请求示例后要输入个人申请的qpi的密钥,密钥是每一个申请的用户都有的独一的一份密钥,在此之前就需要去注册一份个人api用户;然后就是获取成功后的语句,再次设定结果就可以多次获取想要的城市的天气预报了。

在index.js中设定好了如何获取api的数据后就是要设计前端界面了,还是在view标签中写,开始的输入城市栏:<input placeholder="输入城市" name="cityid" bindblur="getCityId">,然后根据index.js中设定的未来天气(future)和当前天气(today)获取温度等信息。

获取的数据:

微信小程序显示天气预报_js

小程序页面:

微信小程序显示天气预报_python_02

3 代码:

代码清单index.wxml

<!--index.wxml-->

<view class="container">

 <view class="search">

   <input placeholder="输入城市" name="cityid" bindblur="getCityId">

   </input>  

 </view>

 <view class="results">

   <view class="sk">

     <view class="city">{{id.id}}</view>

     <view class="temp">温度:{{today.temperature}}</view>

     <view class="power">风力:{{today.power}}</view>

     <view class="info">天气:{{today.info}}</view>

     <view class="direct">风向:{{today.direct}}</view>

   </view>

 </view>

</view>

代码清单:index.wxss

/**index.wxss**/

.search{

 width: 100%;

 height: 100rpx;

 background-color: aqua;

 padding: 15rpx 0;

 box-sizing: border-box;

}

.search input{

 display:block;

 width: 90%;

 height: 70rpx;

 background-color: white;

 margin: auto;

 border-radius: 35rpx;

 text-align: center;

}

代码清单:index.json

// index.js

// 获取应用实例

const app = getApp()

Page({

 /**

  * 页面的初始数据

  */

 data: {

   id:"苏州",

   future:{},

   today:{},

 },

 getCityId:function(event){

   this.setData({

     id:event.detail.value == '' ? '苏州':event.detail.value

   })

   this.getResults()

 },

 getResults:function(){

   let that=this

   wx.request({

     url: 'https://apis.juhe.cn/simpleWeather/query',

     data:{

       city:that.data.id,

       key:'218212d612bf0d45f92c66f47371869f'

     },

     success:function(rsp){

       console.log(rsp)

       that.setData({

         future:rsp.data.result.future,

         today:rsp.data.result.realtime,

       })

     }

   })

 },

 /**

  * 生命周期函数--监听页面加载

  */

 onLoad: function (options) {

   this.getResults();

 },

 /**

  * 生命周期函数--监听页面初次渲染完成

  */

 onReady: function () {

 },

 /**

  * 生命周期函数--监听页面显示

  */

 onShow: function () {

 },

 /**

  * 生命周期函数--监听页面隐藏

  */

 onHide: function () {

 },

 /**

  * 生命周期函数--监听页面卸载

  */

 onUnload: function () {

 },

 /**

  * 页面相关事件处理函数--监听用户下拉动作

  */

 onPullDownRefresh: function () {

 },

 /**

  * 页面上拉触底事件的处理函数

  */

 onReachBottom: function () {

 },

 /**

  * 用户点击右上角分享

  */

 onShareAppMessage: function () {

 }

})

4 结语

本次是利用api在小程序上显示我所想获取的地区的天气。