微信小程序网络请求获取列表数据

问题背景

前篇文章已经介绍了微信小程序如果显示本地列表数据,参考( https://blog.51cto.com/baorant24/6188286 ),本文将介绍如何通过网络请求获取数据,然后在本地列表中显示。

问题分析

(1)微信小程序网络请求的方式 微信小程序发起网络请求的框架代码如下:

wx.request({
      //请求地址
      url: ...,
      //请求头
      header:{
      },
      //请求成功回调
      success(res){
      },
      //请求失败回调
      fail(res){
      }
    })

具体可参考微信官方文档:https://developers.weixin.qq.com/miniprogram/dev/framework/ability/mDNS.html (2)请求的URL和response 本demo选用的URL如下: https://geoapi.qweather.com/v2/city/lookup?location=beij&key=d4a619bfe3244190bfa84bb468c14316 可以直接先访问下了解下返回数据结构: image.png

问题解决

话不多说,直接上代码。 (1)index.js文件,代码如下:

// pages/healdata/healthydata.ts
Page({
  /**
   * 页面的初始数据
   */
  data:{
    code:"0",
    location:[]
  },

   /**
   * 请求网络
   */
  requestNetwork: function(){
    wx.request({
      //请求地址
      url: 'https://geoapi.qweather.com/v2/city/lookup?location=beij&key=d4a619bfe3244190bfa84bb468c14316',
      //请求头
      header:{
        'content-type': 'application/json' //默认值
      },
      //请求成功回调
      success(res){
        var pages = getCurrentPages();
        var index = pages[pages.length - 1];
        index.setData({
          code:res.data.code,
          location: res.data.location
        })
      },
      //请求失败回调
      fail(res){
        console.log(res.errMsg);
      }
    })
  }
})

(2)index.wxml文件,代码如下:

<view>
  <button class="buttonStyle" type="primary" bindtap="requestNetwork">请求网络</button>
  <view>结果返回:{{code}}</view>
  <scroll-view class="scroll-view" scroll-y="true">
  <view class='content1' wx:for="{{location}}" wx:key="this">
    <view class="place">{{item.name}}</view>
    <view>纬度:{{item.lat}}</view>
    <view>经度:{{item.lon}}</view>
  </view>
  </scroll-view>
</view>

(3)index.wxss文件,代码如下:

/* 设置swiper组件的宽高 */
.swiper{
  width: 100%;
  height: 600rpx;
}
/* 设置swiper组件里面图片的宽高 */
.image{
  width: 100%;
  height: 600rpx;
}

.content1{
  /* text-align: center; */
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  margin: 10rpx;
}

.buttonStyle{
  margin-top: 120rpx;
}

.place{
  font-style: italic;
}

运行代码: image.png 点击请求网络按钮: image.png

问题总结

本文介绍了微信小程序如何通过网络请求获取数据,然后在本地列表中进行显示,有兴趣的同学可以进一步深入研究。