data: {
region: [],
locationID: null
},
// 切换城市函数
changeRegion(e) {
this.setData({
region: e.detail.value
})
// 切换完成后调用getLocationID获取城市locationID
this.getLocationID()
// 然后调用getWeather()获取城市天气信息
this.getWeather()
},
// 获取城市locationID
getLocationID() {
wx.request({
url: '###############################',
method: "GET",
data: {
key: "##########################",
location: this.data.region[2],
adm: this.data.region[1]
},
success: (res) => {
this.setData({
// 更新当前城市的locationID
locationID: res.data.location[0].id
})
}
})
},
// 获取天气信息
getWeather() {
wx.request({
url: '#####################',
method: "GET",
data: {
key: "################",
location: this.data.locationID
},
success: (res) => {
console.log(res.data.now)
}
})
},
天气查询小程序
第一个函数切换城市名
第二个函数根据城市名获取对应的locationID
第二个函数根据locationID获取对应的天气
默认的locationID设置为null
输入第一个城市名,得到了城市id1,赋值给变量locationID
等获取天气时拿到的locationID却是初始值null,结果返回undefine
第二次调用的结果是第一次设置的天气,每一次调用的结果都是上一次设置的城市天气......
在request前加上 var that = this,改所有的this为that也是一样的结果
刚刚接触小程序,还望多多指教!
异步的问题,写在setdata的回调里面吧