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後解析並拼湊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時即證實數據已經得到,而後進行下一步操做。記數要記得及時清空,否則容易變成死循環微信小程序