微信小程序 wx.request

onLoad: function () {
var that = this
console.log('https://free-api.heweather.com/s6/weather?location=' + curCity + '&key=fd29112697d54606bd9499e54b05cf1d',)
wx.request({
url: 'https://free-api.heweather.com/s6/weather?location='+curCity+'&key=fd29112697d54606bd9499e54b05cf1d',
headers: {
'Content-Type': 'application/json'
},
success: function (res) { that.setData({
now_weather: res.data.HeWeather6[0].now.tmp,
now_cond: res.data.HeWeather6[0].now.cond_txt,
high_tmp: res.data.HeWeather6[0].daily_forecast[0].tmp_max,
low_tmp: res.data.HeWeather6[0].daily_forecast[0].tmp_min,
for_array: res.data.HeWeather6[0].daily_forecast,
result: 1,
jsonData: JSON.stringify(res.data.HeWeather6[0].daily_forecast) })} }, )},

  这是微信小程序中最经常使用的request请求,一般都是直接在success中设置相关前台参数。如果想要用从接口中获取的数据和本地数据拼凑成数组或者前台对象等,那么就需要等到通过网络通信获得json后解析并拼凑

  但是,由于request请求和其他function是异步的,即request还未执行完就会执行其他function,导致数据在渲染的时候无法获取到正确的,所以针对这个问题,有一个看起来很笨的办法:

 onLoad: function () {
curCity = app.globalData.selectedCity
var that = this
setImage()
console.log(curCity)
var times = setInterval(function () {
if (result) {
console.log(jsonData)
for (var i = 0; i < 8; i++) {
var object1 = new Object();
var json = JSON.parse(jsonData);
// console.log(json)
object1.index = json[i].type
object1.brf = json[i].brf
object1.txt = json[i].txt
object1.img = list2[i] list[i] = object1
//console.log(i)
//console.log(list[i])
console.log(list[i].img)
}
var json2 = JSON.parse(sunJson);
console.log(json2)
forsr = json2.sr
forss = json2.ss
console.log(json2)
clearTimeout(times);//清除计数器
}
that.setData({
for_array: list,
for_sr:forsr,
for_ss:forss
})
}, )
},
})
function setImage() {
var that = this wx.request({
url: 'https://free-api.heweather.com/s6/weather?location='+curCity+'&key=fd29112697d54606bd9499e54b05cf1d',
headers: {
'Content-Type': 'application/json'
},
success: function (res) {
console.log(curCity)
/*that.setData({
now_weather: res.data.HeWeather6[0].now.tmp,
now_cond: res.data.HeWeather6[0].now.cond_txt,
high_tmp: res.data.HeWeather6[0].daily_forecast[0].tmp_max,
low_tmp: res.data.HeWeather6[0].daily_forecast[0].tmp_min,
for_array: res.data.HeWeather6[0].daily_forecast,
result: 1,
jsonData: JSON.stringify(res.data.HeWeather6[0].daily_forecast) })*/
result = 1
jsonData = JSON.stringify(res.data.HeWeather6[0].lifestyle)
sunJson = JSON.stringify(res.data.HeWeather6[0].daily_forecast[0])
//console.log(jsonData)
//setImage()
}
})
}

  在setimage方法中,进行网络连接,如何已经获取到了正确的数据,就把标志位result记为1;同时,在onload函数中,写一个记数循环,当检查到result为1时即证明数据已经获得,然后进行下一步操作。记数要记得及时清空,不然容易变成死循环

上一篇:java提高篇(十一)-----强制类型转换


下一篇:MySql 使用explain分析查询