帮我用layui+python+flask+mysql写一个分页
时间: 2023-07-04 11:29:07 浏览: 170
easyUI+MySQL分页
5星 · 资源好评率100%
好的,以下是一个使用layui+Python+Flask+MySQL实现的分页代码示例:
HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>分页示例</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/layui/2.5.6/css/layui.min.css">
</head>
<body>
<div class="layui-container">
<table class="layui-table">
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>地址</th>
</tr>
</thead>
<tbody id="table_data"></tbody>
</table>
<div id="page"></div>
</div>
<script src="https://cdn.staticfile.org/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/layui/2.5.6/layui.min.js"></script>
<script>
layui.use(['laypage', 'layer'], function(){
var laypage = layui.laypage,
layer = layui.layer;
laypage.render({
elem: 'page',
limit: 10,
curr: 1,
count: 100,
jump: function(obj, first){
if(!first){
$.ajax({
url: '/get_data',
type: 'POST',
dataType: 'json',
data: {
page: obj.curr,
limit: obj.limit
},
success: function(data){
if(data.code == 0){
var html = '';
for(var i=0;i<data.data.length;i++){
html += '<tr>';
html += '<td>'+data.data[i].name+'</td>';
html += '<td>'+data.data[i].age+'</td>';
html += '<td>'+data.data[i].gender+'</td>';
html += '<td>'+data.data[i].address+'</td>';
html += '</tr>';
}
$('#table_data').html(html);
}
else{
layer.msg('获取数据失败!');
}
},
error: function(){
layer.msg('获取数据失败!');
}
});
}
}
});
});
</script>
</body>
</html>
```
Python代码:
```python
from flask import Flask, render_template, request, jsonify
import pymysql
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/get_data', methods=['POST'])
def get_data():
page = request.form.get('page', 1, type=int)
limit = request.form.get('limit', 10, type=int)
offset = (page - 1) * limit
conn = pymysql.connect(host='localhost', user='root', password='123456', database='test', charset='utf8')
cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor.execute('SELECT * FROM users LIMIT %s, %s', (offset, limit))
data = cursor.fetchall()
cursor.execute('SELECT COUNT(*) FROM users')
count = cursor.fetchone()['COUNT(*)']
cursor.close()
conn.close()
return jsonify({'code': 0, 'msg': '', 'data': data, 'count': count})
if __name__ == '__main__':
app.run(debug=True)
```
这个示例使用了jQuery和layui库,通过ajax异步获取分页数据。在Python部分,使用了pymysql库连接MySQL数据库,通过分页查询获取数据并返回给前端。
阅读全文