本文記載瞭如何在微信小程序裏面實現下拉刷新,上拉加載更多ajax
先開看一下界面小程序
大體如此的界面吧。 這個Demo使用了微信的幾個Api和事件,我先列出來。微信小程序
1.wx.request (獲取遠程服務器的數據,能夠理解成$.ajax)服務器
2. scroll-view的兩個事件微信
2.1 bindscrolltolower(滑到頁面底部時)this
2.2 bindscroll (頁面滑動時)url
2.3 bindscrolltoupper (滑倒頁面頂部時)spa
而後咱們看代碼,詳細描述。code
index.jsxml
var url = "http://www.imooc.com/course/ajaxlist"; var page =0; var page_size = 20; var sort = "last"; var is_easy = 0; var lange_id = 0; var pos_id = 0; var unlearn = 0; // 獲取數據的方法,具體怎麼獲取列表數據你們自行發揮 var GetList = function(that){ that.setData({ hidden:false }); wx.request({ url:url, data:{ page : page, page_size : page_size, sort : sort, is_easy : is_easy, lange_id : lange_id, pos_id : pos_id, unlearn : unlearn }, success:function(res){ //console.info(that.data.list); var list = that.data.list; for(var i = 0; i < res.data.list.length; i++){ list.push(res.data.list[i]); } that.setData({ list : list }); page ++; that.setData({ hidden:true }); } }); } Page({ data:{ hidden:true, list:[], scrollTop : 0, scrollHeight:0 }, onLoad:function(){ // 這裏要很是注意,微信的scroll-view必需要設置高度才能監聽滾動事件,因此,須要在頁面的onLoad事件中給scroll-view的高度賦值 var that = this; wx.getSystemInfo({ success:function(res){ console.info(res.windowHeight); that.setData({ scrollHeight:res.windowHeight }); } }); }, onShow:function(){ // 在頁面展現以後先獲取一次數據 var that = this; GetList(that); }, bindDownLoad:function(){ // 該方法綁定了頁面滑動到底部的事件 var that = this; GetList(that); }, scroll:function(event){ // 該方法綁定了頁面滾動時的事件,我這裏記錄了當前的position.y的值,爲了請求數據以後把頁面定位到這裏來。 this.setData({ scrollTop : event.detail.scrollTop }); }, refresh:function(event){ // 該方法綁定了頁面滑動到頂部的事件,而後作上拉刷新 page = 0; this.setData({ list : [], scrollTop : 0 }); GetList(this) } })
index.wxml
<view class="container"> <scroll-view scroll-top="{{scrollTop}}" scroll-y="true" style="height:{{scrollHeight}}px;" class="list" bindscrolltolower="bindDownLoad" bindscroll="scroll" bindscrolltoupper="refresh"> <view class="item" wx:for="{{list}}"> <image class="img" src="{{item.pic_url}}"></image> <view class="text"> <text class="title">{{item.name}}</text> <text class="description">{{item.short_description}}</text> </view> </view> </scroll-view> <view class="body-view"> <loading hidden="{{hidden}}" bindchange="loadingChange"> 加載中... </loading> </view> </view>
源碼奉上 http://pan.baidu.com/s/1gfLpuKj
若是有什麼不明白的能夠直接留言問我, 順便打個廣告,本人承接微信小程序的外包開發或者技術諮詢。 有須要的你們能夠找