欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

微信小程序开发学习笔记 - 4.8 [小案例] 开始使用 wx.request 获取网络请求并渲染到页面

最编程 2024-04-03 10:08:37
...

>>跟着b站up主“咸虾米_”学习微信小程序开发中,把学习记录存到这方便后续查找。

课程连接:4.8.【小案例】初识wx.request获取网络请求并渲染至页面_哔哩哔哩_bilibili

up主提供的网络请求常用接口:

随机猫咪,用来获取一些图片

https://api.thecatapi.com/v1/images/search?limit=1

注意:limit=1则只能获取1张图,设置为非1的任意数可以获取多张图,该小案例设置的是2。

一、wx.request

网络 / 发起请求 / wx.request (qq.com)

二、代码

1、api2.wxml

<view class="out">
  <view class="box" wx:for="{{listArr}}" wx:key="id">
    <view class="pic">
      <image src="{{item.url}}" mode="aspectFill"></image><!--aspectFill显示最短边,多的会裁掉-->
    </view>
    <view class="name">
      姓名:{{item.id}}
    </view>
  </view>
</view>

组件中用wx:for来遍历listArr将图片展出。 item为数组当前项的默认变量名。

2、api2.js中添加如下代码

Page({
  data: {
    listArr:[]
  },

  onLoad(options) {
    this.getData();
  },
  getData(){
    wx.request({
      url: 'https://api.thecatapi.com/v1/images/search?limit=2',
      success:res=>{
        console.log(res.data);
        this.setData({
          listArr:res.data
        })
      }
    })
  },

})

用wx.request发起 HTTPS 网络请求,url为上述up主提供的网络请求常用接口随机猫咪,成功后返回数据data如下图,并将数据赋值给listArr,共有10个对象。

3、api2.wxss

/* pages/api2/api2.wxss */
.out{
  padding:30rpx;
}

.out .box{
  width: 100%;
  height: 500rpx;
  border: 1px solid red;
  margin-bottom: 30rpx;
}
.out .box .pic{
  width: 100%;
  height: 400rpx;
}
.out .box .pic image{
  width: 100%;
  height: 100%;
}
.out .box .name{
  text-align: center;
  line-height: 100rpx;
}

4.结果