上篇说到获取编辑框文本,没看过去看看。
本片介绍简单的接口数据获取,并且展示,采取模拟数据,拉取数据方式方法。文章最后附上DEMO
本篇暂未考虑美化问题,只看功能。如图:
一、简单介绍
1> wx.request 请求接口资源(微信小程序api中的发起请求部分)
2>swiper 实现轮播图的组件 , 一般使用到Banne上,这里先不介绍
3>wx:for 循环语句,将数据循环获取
二、详细说明
1、js请求函数代码(无参请求)
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that = this; //this在函数内部指向变化,所以需要将全局this指向保存到that中
wx.request({
url: 'URL', //需更换需请求数据的接口
method: 'post',//请求方式 OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
headers: {
'Content-Type': 'application/json'
},
success: function (res) {
that.setData({//请求成功后在此刷新,res代表success函数的事件对,data是固定的,stories是是上面json数据中stories
//这里模拟数据
})
},
fail: function (err) { },//请求失败
});
2、.wxml页面代码
<text>我是第三个页面</text>
<view>
<text>模拟请求数据:{{requst}}</text>
</view>
<view class='hotgoodcontainer'>
<view class='gooditem' wx:for="{{hotgoods}}" wx:for-index="idx" wx:for-item="good">
<view class='imgview'>
<image class='productimg' src='{{good.pic_url}}'/>
<text>介绍:{{good.summary}}</text>
</view>
<view>产品名:{{good.name}}</view>
</view>
</view>
3、微信小程序通过api接口将json数据展现到小程序示例,以下为模拟数据
motto: 'MiHome_Store',
userInfo: {},
indicatorDots: true,
autoplay: true,
interval: 3000,
duration: 100,
hotgoods: [{ //模拟接口拉取数据
"name": "90分轻薄羽绒服",
"summary": "防钻绒工艺,保暖更锁温,备好深秋暖意",
"ext_tag": "http://static.home.mi.com/app/shop/img?id=shop_9d57f6e89d1f560b7bce31e0b85a7285.png&w=420&h=240&crop=a_0_120_1080_480&t=png",
"pic_url": "http://static.home.mi.com/app/shop/img?id=shop_48ebe9e693ade1766877e0f8adf425f7.png&w=420&h=240&crop=a_90_0_240_240"
},
{
"name": "红米Note 3",
"summary": "金属机身,指纹解锁,4000mAh大电池",
"ext_tag": "http://static.home.mi.com/app/shop/img?id=shop_d65477ca8db6626da323554e132d7de9.png&w=420&h=240&crop=a_0_120_1080_480&t=png",
"pic_url": "http://static.home.mi.com/app/shop/img?id=shop_c2cf209c66a22818c7f5c269f6bbff12.jpeg&w=420&h=240&crop=a_90_0_240_240",
"url": "http://home.mi.com/shop/detail?gid=95"
},
{
"name": "小米手机5",
"summary": "骁龙820处理器,4轴防抖相机",
"ext_tag": "http://static.home.mi.com/app/shop/img?id=shop_34699befd5c2de3a028eb987fea574e9.png&w=420&h=240&crop=a_0_120_1080_480&t=png",
"pic_url": "http://static.home.mi.com/app/shop/img?id=shop_8dec2f08e5dd9d08b440f77a36e39e16.png&w=420&h=240&crop=a_90_0_240_240"
},
]
4、js请求函数代码(有参请求)
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that = this; //this在函数内部指向变化,所以需要将全局this指向保存到that中
wx.request({
url: 'URL', //需更换需求接口
method: 'post',
data: {
"msg": this.data,//参数
x: '',
y: ''
},
headers: {
'Content-Type': 'application/json'
},
success: function (res) {
that.setData({ //请求成功后在此刷新
//res代表success函数的事件对,data是固定的,stories是是上面json数据中stories
//这里模拟数据
})
},
fail: function (err) {}, //请求失败
});
}
这样最简单方式获取到接口数据
-END