Notes
微信小程序
服务器交互

在本章节中,我们将了解微信小程序如何去拿后端数据库的数据,一般而言,小程序后端有下面两种方式:

  • 微信云开发,接口丰富、便捷,易上手,缺点是要付费,数据掌握在别人手中。
  • 自己的后端。技术难度高,但是可控。

本章节先介绍小程序与后端服务器交互的办法。

向服务器推送数据

这里使用小程序提供的HTTP请求来和服务器建立连接并传递数据。
POST方法详见HTTP报文格式 (opens in a new tab)
使用POST方法发起请求,在页面js中的代码如下:

wx.request({
      url : "https://www.",
      // 服务器地址
      method: "POST",
      data: {
        name: this.data.name,   
        phone: this.data.phone,  
        brand: this.data.brand,  
        modelnumber: this.data.modelnumber,    
        description: this.data.description,    
        isStudent:  JSON.stringify(this.data.isStudent),    //将布尔类型转为json字符串
        id: this.data.id, 
        class: this.data.class, 
        fileList: this.data.fileList,   
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res.data);
        wx.navigateBack({
          delta: 1  //小程序关闭当前页面返回上一页面
        })
        wx.showToast({
          title: '提交完成!',
          icon: 'success',
          duration: 2000
        })
      },
    })

向服务端请求数据

Page({
  data: {
    // 创建数据容器
    list: []
  },
  onLoad: function (options) {
    wx.request({
      url: 'https://test.com',  // 服务器地址
      header: {
        'content-type': 'application/json'
      },
      success: res => {
        console.log(res.data)   // 控制台打印
        this.setData({
          list: res.data    // 赋值
        })
      }
    })
  },
})

然后通过列表渲染到wxml界面:

<view wx:for="{{list}}" wx:key="index">
  <view class="item">
    <view class="number-wrapper">
      <text class="name">{{item.name}}</text>
      <view class="count-wrapper">
        <text class="count">{{item.des}}</text>
      </view>
    </view>
  </view>
</view>

如此,非常简洁地完成了前后端数据的交互。