微信小程序获取天气api,实现天气查询功能

api 地址 https://free-api.heweather.net

我使用的是和风天气免费调取天气的API地址 我们需要进行免费注册,注册后我们进入控制台,拿到key值 **在这我们还需要所调用的api地址放在开发者合法域名中,这需要格外注意 ** 下面就是实现思路,定义基本变量,然后通过wx.request取到数据后,我们通过this.setData方法将局部变量变为全局变量,然后通过双向绑定映射到页面上 下面看下代码吧

1. wxml

<view class="mtop" >
  <button >{
         
  {weather}}</button>
</view>

2.wxss

.mtop{
  margin-top: 180rpx;
}

3.js

Page({

  /**
   * 页面的初始数据
   */
  data: {
    weather:""
  },
  getWeather() {
    var that=this;
    wx.request({
      url: https://free-api.heweather.net/s6/weather/now,
      data: {
        location: 南京,
        key: "b586b23c37b14a83907b6db62e8c9c22"
      },
      success: function (res) {
        that.setData({
          weather: res.data.HeWeather6[0].now.cond_txt
        })
        console.log(res.data)
        
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   this.getWeather();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})

我们可以看下返回的结果 最简单的api查询天气就完成了 总结:1:wx.request的使用 2:尽量学会官方api文档使用 3:var that=this的使用

经验分享 程序员 微信小程序 职场和发展