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
        })
      },
    })
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM