小程序实现天气预报查询

最近在看小程序的开发,虽然好多人已经都会了,但是我刚刚接触,理解不够,所以编写一些简单的小例子来一步步深入理解。

在网上找了一个天气预报的api,然后注册了一下,一共有500次免费的调用机会。暂时还是够用的。哈哈。

附上截图哈:第一张为初始进入小程序;第二张为查询结果。


可能大神们觉得我这个有点简单,但是我刚刚开始起步嘛,所以还是要记录一下的哈。

说一下思路:

1、确定页面布局,一个输入框(用于输入城市的名字),一个按钮(用于查询结果)。

代码大致如下:

< input placeholder= "请输入城市名称" bindinput= 'bindKeyInput' / >
< button bindtap= 'searchWeather'>查询 </ button >

2、在app.js中添加获取天气预报的方法(本项目是getWeather,需要传两个参数,一个是城市的名字,另外一个是回调函数)

代码大致如下:

getWeather: function (city, cb) {
wx.request({
url: 'http://v.juhe.cn/weather/index?format=&key=5ed3c5a7967c34555d2372c3cd1294de&cityname=' + city,
data: {
x: '',
y: ''
},
header: {
"Content-Type": "application/json"
},
success: function (res) {
// console.log(res.data)
console.log( 'success');
cb(res.data);
}
})
}

3、动态获取输入框的值,使用bindinput属性。bindinput='bindKeyInput'

代码大致如下:

bindKeyInput: function(e){
// console.log(e.detail.value)
this.setData({
inputValue: e.detail.value
})
console.log( this.data.inputValue);
}

4、添加按钮的点击事件,使用bindtap事件。在点击查询按钮时,调用获取天气方法

代码大致如下:(我有时候会console.log很多,因为我觉得这样不容易出错,我一般是正式完成之后再删除)

searchWeather: function() {
var thisweather = this;
app.getWeather( this.data.inputValue, function(data){
console.log( 'data');
console.log(data);
console.log( 'data.result');
console.log(data.result);
console.log( 'data.result.future');
console.log(data.result.future);
thisweather.setData({ weatherDatas: data.result.future})
console.log( 'weatherDatas')
console.log(thisweather.data.weatherDatas);
})
}

5、获取到数据后,循环数据,显示到页面区域

代码大致如下:

< scroll-view scroll-y style= "height: 200px;" >
< view wx:for= "{{weatherDatas}}" wx:key= "*this">
日期:{{item.date}}
温度:{{item.temperature}}
星期:{{item.week}}
风向:{{item.wind}}
</ view >
</ scroll-view >
</ view >



以上是用小程序实现的天气查询。可能技术不足,有些地方会有错误,欢迎各位大神指正。

附上我的github地址,可以下载到该例子。gitub地址:https://github.com/shichenyu/miniApps

记得如果觉得可以,可以star一下哦。啦啦啦~

猜你喜欢

转载自blog.csdn.net/scy_fighting/article/details/80821072