我是python flask开发的新手。我正在尝试实现一个服务器端处理数据表,它将从具有1000个记录的mysql数据库表中获取记录。
我希望表格每页显示10行,并查询每个新页面或搜索的服务器/数据库。
这是我的HTML -
<div class="dataTable_wrkld">
<table class="table table-striped table-bordered table-hover" id="dataTables-wrkld">
<thead>
<tr>
<!--<th class="bs-checkbox-1"></th>-->
<th data-align="center">ID</th>
<th data-align="center">Name</th>
<th data-align="center">Total Items</th>
</tr>
</thead>
</table>
</div>
这是我的脚本 -
<!-- DATA TABLES -->
<script>
var table_data = ''
$(document).ready(function() {
$('#dataTables-wrkld').DataTable({
responsive: true,
processing: true,
serverSide: true,
ajax: {
url: '/datatable_change',
type: 'POST',
data: function ( args ) {
return { "args": JSON.stringify( args ) };
},
dataSrc: function (json) {
var arr = Object.keys(json).map(function(k) { return json[k] });
return arr;
},
columns: [
{"data": "ID"},
{"data": "Name"},
{"data": "Items"}
]
}
});
});
</script>
在服务器端,我有 -
@app.route('/datatable_change', methods=['POST'])
def datatable_change():
abc = json.loads(request.values.get("args"))
temp = session.query(Table.id, Table.name, table.total_items).limit(100)
data = Utilities.make_json_dict(['ID', 'Name', 'Items'], temp)
print(json.dumps(data))
return json.dumps(data)
当我运行它时,会触发断点并从DB获取数据。这就是我的json的样子 -
[
{"Items": 31, "ID": 1, "Name": "abc"},
{"Items": 35, "ID": 2, "Name": "def"},
{"Items": 38, "ID": 3, "Name": "ghi"}
.
.
.
]
我用这个答案来格式化我的数据源 - Format ajax dats src
如果我不使用这个,我会得到一个&#34;无法读取属性&#39;长度&#39;未定义..&#34; Jquery错误
运行这一切后, 这是我得到的错误 -
单击OK,这就是我的数据表的样子 -
请注意,没有响应分页。我在浏览器控制台中没有收到任何错误。 我在这做错了什么?请帮忙。
答案 0 :(得分:1)
<强>原因强>
选项columns
不应该是ajax
的子属性,因此缺少右括号}
。
此外,您返回的JSON是针对客户端模式构建的,因此您需要设置serverSide: false
。在服务器端处理模式下,您需要在服务器端进行排序,过滤和排序,返回的数据需要certain structure。
根据您的数据结构,选项dataSrc
应设置为空字符串,即dataSrc: ""
。
<强>样本强>
请参阅this jsFiddle以获取代码和演示。
答案 1 :(得分:1)
我终于让它与服务器端处理一起工作了。在HTML方面,错误是Gyrocode.com在他的回答中提到的。但我更改了serverSide:True以及返回的数据格式。
在服务器端,有python模块负责处理必要的表事件 - python datatables module
但是这个模块是为python金字塔框架编写的。需要进行一些小的改动才能使它与烧瓶一起使用。
这是最终代码 -
$('#dataTables-server').DataTable({
responsive: true,
processing: true,
serverSide: true,
ajax: {
url: '/datatable_change',
method: 'post',
data: function(args) {
return {
"args": JSON.stringify(args)
};
}
},
columns: [
{ "data": "ID" },
{ "data": "Name" },
{ "data": "Items" }
]
});