layui之数据表格–与后台交互获取数据的方法
时间: 2024-02-06 10:09:45 浏览: 22
要让 layui数据表格与后台交互获取数据,你需要在前端发送一个 AJAX 请求给后台,然后在后台处理数据并返回给前端。以下是一个简单的例子,展示了如何使用 layui数据表格与后台交互获取数据。
前端代码:
```javascript
layui.use('table', function(){
var table = layui.table;
//第一个实例
table.render({
elem: '#demo',
url: '/getdata', //数据接口
page: true, //开启分页
cols: [[ //表头
{field: 'id', title: 'ID', width:80, sort: true, fixed: 'left'},
{field: 'username', title: '用户名', width:120},
{field: 'email', title: '邮箱', width: 150},
{field: 'sex', title: '性别', width:80, sort: true},
{field: 'city', title: '城市', width:100},
{field: 'sign', title: '签名', width: 200},
{field: 'experience', title: '积分', width: 80, sort: true},
{field: 'score', title: '评分', width: 80, sort: true},
{field: 'classify', title: '职业', width: 100},
{field: 'wealth', title: '财富', width: 135, sort: true},
{fixed: 'right', title:'操作', toolbar: '#barDemo', width:150}
]]
});
});
```
在上面的代码中,我们指定了数据接口的 url 为 /getdata,这个接口将会返回一个 JSON 格式的数据。
后台代码(使用 Flask 框架):
```python
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/getdata')
def get_data():
data = [
{'id': 1, 'username': 'user1', 'email': 'user1@example.com', 'sex': '男', 'city': '北京', 'sign': '签名1', 'experience': 100, 'score': 80, 'classify': '程序员', 'wealth': 10000},
{'id': 2, 'username': 'user2', 'email': 'user2@example.com', 'sex': '女', 'city': '上海', 'sign': '签名2', 'experience': 80, 'score': 90, 'classify': '设计师', 'wealth': 20000},
{'id': 3, 'username': 'user3', 'email': 'user3@example.com', 'sex': '男', 'city': '深圳', 'sign': '签名3', 'experience': 120, 'score': 70, 'classify': '作家', 'wealth': 30000},
{'id': 4, 'username': 'user4', 'email': 'user4@example.com', 'sex': '女', 'city': '广州', 'sign': '签名4', 'experience': 80, 'score': 60, 'classify': '诗人', 'wealth': 40000},
{'id': 5, 'username': 'user5', 'email': 'user5@example.com', 'sex': '男', 'city': '北京', 'sign': '签名5', 'experience': 150, 'score': 30, 'classify': '画家', 'wealth': 50000}
]
return jsonify(data)
if __name__ == '__main__':
app.run()
```
在上面的代码中,我们定义了一个 /getdata 的路由,它会返回一个包含 5 个用户信息的列表。
这样,当你在浏览器中打开页面时,数据表格就会自动从后台获取数据并进行显示。