您的当前位置:首页正文

零基础学小程序003----请求服务器数据,请求后台json数据

来源:图艺博知识网

点击下面网址进入系列教程

我们开发小程序,肯定不是简简单单的写一些页面,肯定会设计到一些和后台服务器的交互,今天就带大家来学习小程序请求后台数据。
学习要点

  • 1,通过https请求后台数据
  • 2,解析json数据
  • 3,获取https数据

一,我们通常请求后台的数据如下:

image image

二,小程序请求后台json数据代码实现

先看效果图

image

实现代码api.js


Page({

  /**
   * 页面的初始数据
   */
  data: {
    
  },
  //请求简单数据
  getData:function(e){
    console.log('开始加载服务器数据')
    var that = this;
    var jsonStr = "";
    wx.request({
      url: 
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res.data)
        //json对象转字符串
        jsonStr = JSON.stringify(res.data)

        that.setData({
          text: '后台返回的数据如下: \n'+jsonStr,
        })
      }

    })
  },
//请求复杂json数据
  getjson: function (e) {
    console.log('开始加载服务器数据')
    var that = this;
    var jsonStr = "";
    wx.request({
      url: 
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res.data)
        //json对象转字符串
        jsonStr = JSON.stringify(res.data)

        that.setData({
          json: '后台返回的数据如下: \n' + jsonStr,
        })
      }

    })
  },


})

api.wxml

<button bindtap='getData'>https请求简单数据</button>
<text>{{text}}</text>
<button bindtap='getjson'>请求后台json数据</button>
<text>{{json}}</text>
代码结构.png

由于是入门,所以代码特别少,但是基本的请求后台数据的功能都实现了

Top