第一次写微信小程序在开发过程中,想要定义一个函数请求天气api并返回数据
思路代码(错误示例)
function getWeatherData(cityName){
var data={};
wx.request({
url: 'https://www.sojson.com/open/api/weather/json.shtml?city=' + cityName,
success:function(res){
data = res.data;
}
});
return data;
}
这种写法是不正确的,并不能将响应的结果传给data
后改成这种写法
function getWeatherData(cityName,callback){
var rr={};
wx.request({
url: 'https://www.sojson.com/open/api/weather/json.shtml?city=' + cityName,
success:function(res){
callback(res.data);
}
});
}
在callback中对响应的数据进行处理
感谢刘明华先生的分享,好东西应该分享出来。