一个简单的微信小程序天气预报查询
仅以此记录自己学习小程序的过程,以及学习中所遇到的问题既解决过程给其他新手以参考
所需要用到的标签有input输入框,用来获取城市的名称
icon标签用来表示搜索图标,已经用来和接口发生响应
**前导知识
wx.request用来发起网络请求。默认超时时间和最大时间都是60s,一个微信小程序同时最多只能连接5个网络请求
下面用代码来演示一下wx.request的使用
wx.request({
url:'test', //api接口地址
data:{
}, //用来请求的参数
method:'POST' //HTTP的请求方法
header:{
'content-type':'application/json' //默认值
},
success(res){
console.log(res.data) //接口调用成功的回调函数
}
})
获取输入的城市名
wxml页面
<input placeholder="请输入城市名查询" bindinput="bindInput"></input>
<view class="icon">
<icon type="search" size="26" bindtap="search"/>
</view>
js页面
首先定义一些变量,用来保存获取到的数值
//定义城市、天气、温度、风级、图片、日期参数
var defaultcity,getweather,gettemp,getwind,getpic,getdate
//定义bindInput函数 用来获取input输入框的值
bindInput:function(e){
defaultcity=e.detail.value
}
连接api接口请求天气预报的数据
由前导知识可得
search:function(e){
var that = this
wx.request({
url:'接口地址+key+参数' +defaultcity,
sueecss(res){
getweather = res.data.results[0].weather_data[0].weather
gettemp = res.data.results[0].weather_data[0].temperature
getwind = res.data.results[0].weather_data[0].wind
getpic = res.data.results[0].weather_data[0].dayPictureUrl
getdate = res.data.results[0].weather_data[0].date
that.setData({
city:defaultcity,weather:getweather,
temp: gettemp,wind:getwind,
pic : getpic,date: getdate
})
}
})
}
最后渲染界面展示数据
<view class="body">
<view class="city"><text>{{city}}</text> </view>
<view class="date"><text>{{date}}</text> </view>
<view>
<image src="{{pic}}" mode="aspectFit"/>
</view>
<view class="buttom">
<view class="weather"><text>{{weather}}</text> </view>
<view class="wind"><text>{{wind}}</text> </view>
<view class="temp"><text>{{temp}}</text> </view>
</view>
</view>
有想一起学习小程序的可以加我咱们一起讨论进步