关于如何将wx.request中的success函数获得的数据赋值给外部变量并return出去
问题描述:
#从后端获取数据
getNews:function(link){
var pagelist = [];
wx.request({
url: 'http://127.0.0.1:8000/api/getartlist',
header:{"Content-Type": "application/x-www-form-urlencoded"},
method: 'POST',
data:{'url':link},
success: res => {
console.log("123"+res.data['artlist'])
pagelist = res.data['artlist']
}
})
return pagelist
#调用上面的函数获取数据
initNews:function(){
console.log("Getting news...");
var url = 'https://www.ojc.zj.cn/Col/Col1108/Index_1.aspx';
// 从第一页获取新闻列表(需要年,月日,标题,简介)
var onePageList = [];
onePageList = this.getNews(url)
this.setData({
pageIndex : 1
})
// 将新增页的内容合并到新闻列表中
this.data.newsList = this.data.newsList.concat(onePageList);
console.log("new:"+this.data.newsList)
this.setData({
newsList: this.data.newsList,
loading: false
});
},
这样写不行,return的是个空值。我也试了好多方法也不行。
求解答
答
success函数是异步获得数据的,不能用return返回出去。要用回调函数的形式返回数据
类似这样
getNews:function(link,callback){
var pagelist = [];
wx.request({
url: 'http://127.0.0.1:8000/api/getartlist',
header:{"Content-Type": "application/x-www-form-urlencoded"},
method: 'POST',
data:{'url':link},
success: res => {
console.log("123"+res.data['artlist'])
pagelist = res.data['artlist']
callback(pagelist);
}
})
},
initNews:function(){
console.log("Getting news...");
var url = 'https://www.ojc.zj.cn/Col/Col1108/Index_1.aspx';
// 从第一页获取新闻列表(需要年,月日,标题,简介)
this.getNews(url,(onePageList) => {
this.setData({
pageIndex : 1
})
// 将新增页的内容合并到新闻列表中
this.data.newsList = this.data.newsList.concat(onePageList);
console.log("new:"+this.data.newsList)
this.setData({
newsList: this.data.newsList,
loading: false
});
});
},
如有帮助,望采纳!谢谢!
答
你要定义全局变量,然后把取到的值设置给全局变量即可。
答
用Promise