文章目录
前言
一、模块flow
二、使用步骤
信息流加载的解决方案
2.API数据示例
3.PHP后端代码
4.核心代码
总结
前言
layui.flow,模块包含信息流加载和图片懒加载两大核心支持,无论是对服务端、还是前端体验,都有非常大的性能帮助。
一、模块flow
模块加载名称:flow
layui.use('flow', function(){ var flow = layui.flow; //信息流 flow.load(options); //图片懒加载 flow.lazyimg(options); });
二、使用步骤
1.信息流加载的解决方案
HTML容器构造
<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no"> <title>信息流</title> <!--layui封装库--> <script src="js/layui/layui.js" charset="utf-8"></script> <link rel="stylesheet" href="js/layui/css/layui.css">
<ul class="flow-default" id="lock_data"></ul>
2.API数据示例
{ "err": "", "res": "", "data": [ { "depart_id": "12", "province": "山东省", "city": "济南市", "area": "历下区", "user_name": "张思", "user_url": "upload/photo/1065_cf9f8858d59740b387b6f78581522201.JPG" } ], "code": 0, "count": 112 }
3.PHP后端代码
根据前端代码需求,开发对应的API接口。其中page是通过get方式获取的,在实际生产环境中,注意过滤参数,防止SQL注入即可
public function getMarkers() { global $db, $res; dbc(); @$p = $_GET['page'] == "" ? 1 : $_GET['page'];//获取用户选择的页码 @$pagesize = $_GET['limit'] == "" ? 15 : $_GET['limit'];//获取用户选择的每页显示多少条数据 @$limit = ($p - 1) * $pagesize;//偏移量 //获取数据; $sql = "select a.depart_id,a.depart_name,a.province,a.city,a.area,a.depart_address,a.poi_lng,a.poi_lat,b.depart_id,b.user_id,b.user_name,b.user_url FROM " . $db->table('depart') . " AS a, " . $db->table('user') . " AS b WHERE a.depart_id = b.depart_id"; $sql .= " ORDER BY a.depart_id LIMIT " . $limit . "," . $pagesize; $row = $db->queryall($sql); //获取总记录; $sql_c = "select a.depart_id,b.depart_id FROM " . $db->table('depart') . " AS a, " . $db->table('user') . " AS b WHERE a.depart_id = b.depart_id"; $sql_c .= " ORDER BY user_depart"; $row_c = $db->queryall($sql_c); $res['code'] = 0; $res['count'] = count($row_c); $res["data"] = $row; die(json_encode_lockdata($res)); }
4.核心代码
layui.use('flow', function () { var $ = layui.jquery; var flow = layui.flow; flow.load({ elem: '#lock_data' //指定列表容器 , end: '数据加载完毕' //没有数据的提示文字 , isAuto: false , done: function (page, next) { //到达临界点(默认滚动触发),触发下一页 console.log(page) var lis = []; $.getJSON('http://test.com/flow/api/api.php?act=getMarkers&token=3cab7ce4142608c0f40c785b5ab5ca24&page=' + page, function (res) { layui.each(res.data, function (index, item) { lis.push('<li>' + item.user_name + '</li>'); }); //pages为Ajax返回的总页数,只有当前页小于总页数的情况下,才会继续出现加载更多 next(lis.join(''), page < res.count / 15); }); } }); });
总结
在参考官方案例时,需要注意 next(lis.join(''), page < res.count / 15);
pages为Ajax返回的总页数,只有当前页小于总页数的情况下,才会继续出现加载更多,按照实际传参为准。