request请求调用后台接口、后台数据的导入(一)

通过request调用接口实例(一)

查看对应的接口文件,用JsonView格式化JSON文件。我们可以看到对应Json文件有相应的root路径,以图片地址为例,一个完整的图片链接应该是root+thmb。

<block wx:for="{{contents}}">
<view>
<text>{{item.id}}---{{item.ttl}}</text>
<image src="https://clouddn.com/{{item.thmb}}"></image>
<!--图片和音频的加载都需要加入root路径-->
</view>
</block>
Page({
  data: {
    contents: {}
  },
  onLoad: function (option) {
    var _this = this;//我们通过将当前对象赋给一个新的对象var _this = this;然后使用_this 来setData就行了
    wx.request({
      url: 'https://test.xxxxx.com/shanpian.html?method=sptype',//这个url我们对应后台给的接口地址
      data: {},
      method: 'GET',
      header: {
        'content-type': 'application/json'//默认值
      },
      //请求后台数据成功
      success: function (res) {
        console.log(res);
        _this.setData({  //因为this作用域指向问题,success函数实际上是一个闭包,无法直接通过this来setData,所以我们再前面定义_this
          contents: res.data.msg
        })
      },
      fail: function ({ errMsg }) {
        console.log('request fail', errMsg)
        _this.setData({
          loading: false
        })
      },
    })
  }
}

猜你喜欢

转载自www.cnblogs.com/EdisonVan/p/9084422.html