鉴于网上layui table分页后端部分很少,官网上的例子也没解释后端部分如何写,容易让初学者误会后端部分不需要写分页,为什么怎么写limit都不起作用。前后端都需要写!!!!
我使用的Python web,使用的是flask
我的demo目录如下
---layuiTest
------data
--------user.json
---static
---template
------index.html
---index.py
1、index.html引入layui,前端分页
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>layuitest</title> <link href="{{url_for('static',filename='layui/css/layui.css')}}" rel="stylesheet"> <script src="{{url_for('static',filename='layui/layui.js')}}"></script> </head> <body style="padding-top: 20px;padding-left: 20px"> <h2>练习layui</h2> <div id="test1"></div> <script> layui.use('table', function(){ var table = layui.table; table.render({ elem: '#test1' ,url: '/user' //数据接口 ,page: true //开启分页 ,limit:4 ,limits:[4,8,12] ,cols: [[ //表头 {field: 'id', title: 'ID', width:80, sort: true, fixed: 'left'} ,{field: 'username', title: '用户名', width:80} ,{field: 'sex', title: '性别', width:80, sort: true} ,{field: 'city', title: '城市', width:80} ,{field: 'sign', title: '签名', width: 177} ,{field: 'experience', title: '积分', width: 80, sort: true} ,{field: 'score', title: '评分', width: 80, sort: true} ,{field: 'classify', title: '职业', width: 80} ,{field: 'wealth', title: '财富', width: 135, sort: true} ]] }); }); </script> </body> </html>
2、index.py,后端分页
# -*- coding: utf-8 -*- from flask import Flask,json, request import json app = Flask(__name__) app.config['JSON_AS_ASCII'] = False @app.route("/") def index(): return render_template("index.html") @app.route("/user",methods=['GET']) def user(): page = int(request.args["page"]) limit = int(request.args["limit"]) try: with open('./data/user.json',encoding='utf-8') as f: jsonStr=json.load(f) jsonStr["count"] = len(jsonStr["data"]) jsonStr["data"] = jsonStr["data"][(page - 1) * limit: page * limit] return jsonStr except Exception as e: print(e) return jsonify({"code": "500"}) if __name__ == '__main__': app.run()