尝试了好久,终于实现了使用layui的table将后端的数据显示出来了。
html中添加表格:
<table id="demo" lay-filter="test"></table>
script中绑定数据:
<script>
layui.use('table', function(data){
var table = layui.table;
//第一个实例
table.render({
elem: '#demo'
,height: 312
,url: '/show_list' //数据接口
{#cols设置的首行中每一列的标题,注意field里面的名称一定要在后端指定出来,必须数据相对应,这样数据才能在前端显示出来,sort表示排序#}
,cols:[[
{field:'address',title:'存放地址',sort:true}
,{field:'xgtm',title:'修改时间'}
,{field:'xgjd',title:'执行进度'}
]],
page: {
layout: ['count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
{#, groups: 2#}
, limit: 5
{#这里limit设置一页多少行数据,前后端都要设置#}
}
,even: true //开启隔行背景
,text:{
none:'暂无相关数据,请先上传'
}
});
});
</script>
这里是后端数据传递
@app.route('/show_list')
def showlist():
cursor=connect_mysql()
sql2 = 'select count(*) from wd_record'
cursor.execute(sql2)
for item in cursor:
count = item[0]
page = request.args.get('page', '1')
limit = request.args.get('limit', '5')
# limit后面的数据实际上是在如果前端没有数据传来的时候的默认值
sql='select * from wd_record limit '+str((int(page)-1)*int (limit))+','+limit
cursor.execute(sql)
ans=cursor.fetchall()
ans1=list(ans)
zwlist=[]
for temp in ans1:
ans1[ans1.index(temp)]=list(temp)
for temp in ans1:
#这里由于数据库中时间的存储是datetime类型,直接传递并不能传递到前端,进行时间转换有点麻烦,然后就直接将其强制转换为字符串类型就可以传递到前端了
temp[1]=str(temp[1])
# 注意下面这个一定要指出来,而且名称应该和前面的数据名称相对应
jlist={'address':temp[0],'xgtm':temp[1],'xgjd':temp[2]}
zwlist.append(jlist)
print('这是查询所有的语句')
cursor.close()
# count表示数据条数,会在前端显示,data里面传的是数据
return json.dumps({'code':0,'msg':'','count':count,'data':zwlist})
然后运行出来的结果如下