上一节实现了循环列表数据渲染到视图,并给列表每一项添加了路由导航到新页面查看更多细节,但是目前我们的数据都是虚拟的,现在我们就开始利用微信的request请求来接收豆瓣电影接口提供的数据。API: wx.request(OBJ ...
参数有7个,这里主要讲一下几个重要的:
onLoad: function() {var url=https://api.douban.com/v2/movie/top250;var that = this;//确保回调函数this的指向正确,后面会以es6的箭头函数代替wx.request({url:url, //KEY和KEY值相同可简写为urldata: {}, //不要求数据header: { 'Content-Type': 'application/json' },//成功时的回调,res为返回值,需要储存到我们的data数据里面success: function(res) {that.setData({moivelist: res.data.subjects,loading: true})}})}
<loading hidden="{{loading}}">加载中....</loading>
onLoad: function(options) {var that = this;var address = 'https://api.douban.com/v2/movie/subject/';wx.request({url: address + options.id,data: {},header: { 'Content-Type': 'application/json' },success: function(res) {that.setData({item: res.data,loading: true})}})}
<import src="../temple/temple.wxml"></import>
<loading hidden="{{loading}}">
加载中....
</loading>
<view class="searchWrap">
<view class="inputWrap">
<icon type="search" size="20"/>
<input placeholder="请输入搜索内容" value="{{content}}" type="text" placeholder-style="custom-placeholder-style" placeholder-class="custom-placeholder-class" bindinput="inputing" bindblur="quick"/>
</view>
<view class="cancel" bindtap="searching">{{cancel}}</view>
</view>
<scroll-view class="main" scroll-y="true" bindscrolltoupper="" bindscrolltolower="" bindscroll="" scroll-into-view="" scroll-top="">
<block wx:for="{{moivelist}}">
<template is="try" data="{{item}}"></template>
</block>
</scroll-view>
data: {moivelist: [],loading: true,cancel: "取消",search: ""},inputing: function(event) {if (event.detail.value) {this.setData({cancel: "搜索"})} else {this.setData({cancel: "取消"})}},//失去焦点事件quick: function(event) {if (!event.detail.value) {this.setData({cancel: "取消"})} else {this.setData({search: event.detail.value})}},//点击搜索事件searching: function() {if (this.data.cancel === "取消") {wx.hideKeyboard()} else {this.setData({loading: false})wx.request({url: url + this.data.search,data: {},header: { 'Content-Type': 'application/json' },success: function(res) {that.setData({moivelist: res.data.subjects,loading: true})}})}}
创建一个util文件夹,在里面创建一个util.js文件,用来放我们的方法。
function getData(address,datas,cb){
wx.request({
url: address,
data:datas,
header: { 'Content-Type': 'application/json' },
success: cb
})
}
module.exports = {
getData: getData
}
onLoad: function() {util.getData(url,{},(res)=>{this.setData({moivelist: res.data.subjects,loading: true})})}