使用方法wx.request请求之后返回我需要的数据
时间: 2024-04-03 21:35:45 浏览: 58
在使用wx.request请求之后,我们需要在回调函数中处理返回的数据。以下是一个示例代码:
```
wx.request({
url: 'https://example.com/api/data',
success: function(res) {
console.log(res.data); // 返回的数据
// 在这里进行数据处理
},
fail: function(res) {
console.log(res.errMsg); // 错误信息
}
})
```
在上述代码中,我们在success回调函数中使用console.log输出了返回的数据。然后我们可以在这个回调函数中进行数据处理,比如解析JSON数据、渲染页面等等。
当我们获取到返回的数据后,可以使用wx.showToast、wx.showModal等方法提示用户,或者直接将数据展示在页面中。以展示在页面中为例,我们可以在success回调函数中使用setData方法将数据设置到页面的data属性中,然后在页面中调用这些数据。
示例代码如下:
```
Page({
data: {
dataList: []
},
onLoad: function() {
var that = this;
wx.request({
url: 'https://example.com/api/data',
success: function(res) {
console.log(res.data); // 返回的数据
that.setData({
dataList: res.data
})
},
fail: function(res) {
console.log(res.errMsg); // 错误信息
}
})
}
})
```
在上述代码中,我们在页面的data属性中定义了一个名为dataList的空数组。然后在onLoad生命周期函数中发起了一个请求,并在success回调函数中使用setData方法将返回的数据设置到dataList中。最后,在页面中可以使用{{dataList}}来调用这些数据。
阅读全文
相关推荐


















