内容:实现api接口的连接与获取数据请求的具体内容,实现天气预报页面的设计。
index.html
<!--index.wxml-->
<text>{{yiyan.hitokoto}}</text>
<text>--《{{yiyan.from}}》</text>
<button bindtap='click'>点击发起天气api请求</button>
<view class='container' wx:if="{{flag}}">
<view class='padb' style='font-size:16px; font-weight:bold;'>{{weather.city}}实况天气预报</view>
<view>气象台 {{weather.update_time}} 更新</view>
<view class='padb'>{{weather.data[0].tem}} {{weather.data[0].wea}}</view>
<view class='padb'>{{weather.win}} {{weather.win_speed}} {{weather.win_meter}}</view>
<view class='padb'>穿衣指数: {{weather.data[0].index[3].level}}</view>
<view class='padb'>{{weather.data[0].index[3].desc}}</view>
<view class='padb'>洗车指数: {{weather.data[0].index[4].level}}</view>
<view class='padb'>{{weather.data[0].index[4].desc}}</view>
<view class='padb'>空气质量 {{weather.data[0].air_level}} 空气指数 {{weather.data[0].air}}</view>
<view class='padb'>{{weather.data[0].air_tips}}</view>
<view class='padb' style='font-size:16px; font-weight:bold;'>{{weather.city}}七日天气</view>
<block wx:for='{{weather.data}}' wx:key='key_list'>
<view class='padb'>{{item.day}} - {{item.date}} - {{item.week}}</view>
<view class='padb'>{{item.wea}} -{{item.tem1}}/{{item.tem2}}</view>
</block>
<view class='padb' style='font-size:14px; color:#666;'>TianqiAPI.com</view>
</view>
index.wxss
/**index.wxss**/
.userinfo {
display: flex;
flex-direction: column;
align-items: center;
}
.userinfo-avatar {
width: 128rpx;
height: 128rpx;
margin: 20rpx;
border-radius: 50%;
}
.userinfo-nickname {
color: #aaa;
}
.usermotto {
margin-top: 200px;
}
.container {
height: 100%;
text-align:center; background:#f6f8f8; padding:20rpx;font-size:16px;
}
.padb{
padding-bottom: 15rpx;
}
.container>view{
font-size: 30rpx;
height: 80rpx;
display: flex;
align-items: center;
border-bottom: 1rpx solid #999999;
}
index.js
//index.js
//获取应用实例
const app = getApp()
Page({
data: {
msg:'Home',
id:'txt',
motto: 'Hello World',
userInfo: {},
index:9,
yiyan:{},
weather:{},
flag:false,
hasUserInfo: false,
imgurl: [
{url:"../../assets/icons/bg1.jpg"},
{url: "../../assets/icons/bg2.png"},
{url: "../../assets/icons/shuimo.jpg"},
{url: "../../assets/icons/emm.jpg"}
],
canIUse: wx.canIUse('button.open-type.getUserInfo'),
obj:{
name:"hp",
index:"0",
time:"18"
}
},
click:function(){
var that = this;
wx.request({
url:'https://v1.hitokoto.cn/',
data:{
x:'',
y:'',
},
header:{
'content-type':'application/json' //默认值
},
success(res){
console.log(res.data)
that.setData({
yiyan:res.data
})
}
});
wx.request({
url: 'https://www.tianqiapi.com/api/',
method:'get',
dataType:'json',
data: {
version:'v1',
city:'湛江'
},
header: {
'content-type': 'application/json' //默认值
},
success(res) {
console.log(res.data)
that.setData({
weather: res.data,
flag:true,
})
}
})
onLoad: function () {
var that = this;
wx.request({
url: 'https://v1.hitokoto.cn/',
data: {
x: '',
y: '',
},
header: {
'content-type': 'application/json' //默认值
},
success(res) {
console.log(res.data)
that.setData({
yiyan: res.data
})
}
})
}
})
实习效果: