tp5+ajax 结合上拉加载功能,上拉加载在微信小程序里面是最常见的了,今天就来说下网页上的上拉加载。
前端代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0" name="viewport"> <title>上拉加载</title> <script src="/public/static/tpl/index/foundation/js/jquery.js?ver19.4.48"></script> <script src="iscroll.js"></script> <link rel="stylesheet" href="app.css"> <script type="text/javascript"> function fontSize(){ var deviceWidth=document.documentElement.clientWidth>640?640:document.documentElement.clientWidth; document.documentElement.style.fontSize=(deviceWidth/25)+"px"; } fontSize(); window.onresize=fontSize; </script> </head> <body> <div id="wrapper"> <div id="scroller"> <ul class="p1_list"> </ul> <div class="clearboth"></div> <div class="pull-loading"> 上拉加载 </div> </div> </div> <script> $(function(){ $.ajax({ //请求方式 type:'GET', //发送请求的地址 url:'https://www.tpxhm.com/wxapi/Weixin/ajaxvote10', //服务器返回的数据类型 dataType:'json', //发送到服务器的数据,对象必须为key/value的格式,jquery会自动转换为字符串格式 data:'', success:function(data){ console.log(data.num10); var arrlist=data.num10; for(var p in arrlist){ $('.p1_list').append('<li><img src="'+arrlist[p].img+'" alt=""><p>'+arrlist[p].title+'</p></li>') } } }); }) </script> <script type="text/javascript"> var myscroll = new iScroll("wrapper", { onScrollMove: function () { //拉动时 //上拉加载 if (this.y < this.maxScrollY) { $(".pull-loading").html("释放加载"); $(".pull-loading").addClass("loading"); } else { $(".pull-loading").html("上拉加载"); $(".pull-loading").removeClass("loading"); } }, onScrollEnd: function () { //拉动结束时 //上拉加载 if ($(".pull-loading").hasClass('loading')) { $(".pull-loading").html("加载中..."); pullOnLoad(); } } }); // 上拉加载函数,ajax var num = 10; var page = 4; //每次加载4条 function pullOnLoad() { setTimeout(function () { $.ajax({ url: "https://www.tpxhm.com/wxapi/Weixin/ajaxvote", type: "get", dataType: 'json', success: function (data) { // console.log(data); var datares=data.re var data_length = datares.length;//数据的总长度 var remainder = data_length % page;//余数 if ( data_length >= (num+page)){ for (var j = num; j < num + page; j++){ $('.p1_list').append('<li><img src="'+datares[j].img+'" alt=""><p>'+datares[j].title+'</p></li>') } num+=page; }else if (remainder != 0 && data_length-num == remainder){ for (var j = num; j < num + remainder; j++){ $('.p1_list').append('<li><img src="'+datares[j].img+'" alt=""><p>'+datares[j].title+'</p></li>') } num+=page; }else{ $('.pull-loading').html("没有了哟"); } myscroll.refresh(); }, error: function () { console.log("出错了"); } }); myscroll.refresh(); }, 500); } </script> </body> </html>
Demo:下拉demo(点击预览)
后端代码:
public function ajaxvote10(){ $num10=db('noteajax')->order('id desc')->field('img,title')->limit(10)->select(); return json(['code'=>200,'msg'=>'success','num10'=>$num10]); } public function ajaxvote(){ $re=db('noteajax')->order('id desc')->field('img,title')->select(); return json(['code'=>200,'msg'=>'success','re'=>$re]); }
文章评论(0)