1、首先 導入DataTable 的插件
2、定義表結構:
HTML:
<table>
<thead>
<tr>
<th>id</th>
<th>任務名稱</th>
<th>狀態</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JS:
var myparas = "?stime="+GetIt["stime"]+"&etime="+GetIt["etime"]+"&which="+GetIt["which"]+"&due="+GetIt["due"];
var table = $("datatable-buttonss").DataTable({
"lengthMenu": [16, 32, 48], // 定義每頁展示數據數量
"aaSorting": [[ 2, "desc" ]], // 初始化根據第3列降序排列
"searching": true, //全文搜索
"bPaginate": true, //翻頁功能
"bInfo": true, //頁腳信息
"bAutoWidth": false,//自動寬度
"bProcessing": true, //DataTables載入數據時,是否顯示‘進度’提示
ajax:"/task_mgm/taskDataMine2" + myparas, // ajaxs向后台請求數據
"columnDefs":[ // 自定義列功能
{
"targets": [ 0 ], //目標列
"Sorting": false, // 是否支持排序
"width": "5%", // 列寬
"visible": false, // 列不可見
},
{
"targets": [ 1 ],
"Sorting": false,
"render": function ( data, type, row, meta ) // data:表格數據 row:該行所有數據 數組形式 所以 data==row[1]
{return type === 'display' && data.length > 20?'<span title="'+data+'">'+data.substr( 0, 16 )+'...</span>' :data;}
}, // 給長字符串加省略號
{
"targets": [ 2 ],
"width": "28%",
"orderable": false,
"defaultContent": '<i class="fa fa-edit" id="edit">編輯</i> <i class="fa fa-times" id="delete">刪除</i> <i class="fa fa-star-o" id="focus">關注</i> <i class="fa fa-share-square-o" id="share">分享</i>',
"render": function (data, type, full) {
if(data == 0){return '<i class="fa fa-edit" id="edit">編輯</i> <i class="fa fa-times" id="delete">刪除</i> <i class="fa fa-star-o" id="focus">關注</i> <i class="fa fa-share-square-o" id="share">分享</i>';}
else {return '<i class="fa fa-edit" id="edit">編輯</i> <i class="fa fa-times" id="delete">刪除</i> <i class="fa fa-star" id="focus">已關注</i> <i class="fa fa-share-square-o" id="share">分享</i>';}
}
},
]
})
<script>
// 獲取任務id 來編輯任務的 兩種方式:
$(function){
// 1) 通過 編輯按鈕 編輯任務
$("#datatable-buttonss tbody").on('click', '#edit', function () {
var data = table.row($(this).parents('tr')).data(); //獲取本行數據 數組形式
window.location.href='/task_mgm/taskinfo_editID='+data[0]; // data[0] 第一列數據 即后端傳來的任務id
});
// 2) 通過 點擊任務名 通過a標簽鏈接編輯任務
{
"targets": [ 1 ],
"sorting": false,
"render": function(data, type, full) { // full 以數組形式存放本行數據 full[0]:任務id full[1]:任務名
return '<a id="shareInfo" href="/task_mgm/taskinfo_editID='+full[0]+'">'+ full[1] +'</a>'}
// 3) 通過1,2方法的組合 即點擊任務名 觸發事件
{
"targets": [ 1 ],
"sorting": false,
"render": function(data, type, full) { // full 以數組形式存放本行數據 full[0]:任務id full[1]:任務名
return '<a id="shareInfo" href="#'">'+ full[1] +'</a>'
}
$("#datatable-buttonss tbody").on('click', '#shareInfo', function () {
var data = table.row($(this).parents('tr')).data();
window.location.href="/task_mgm/taskinfo_editID="+data[0];
});
}
</script>
后端flask:
返回的數據格式:['data': [ [0, '第一個任務',0], [1, ‘第二個任務’, 0], [2,‘第三個任務’,1]] ]
所以要用工具函數構造此數據, 然后調用該函數返回數據:
def sql3json(objs, fields): # objs是查詢的數據庫對象tasks fields是包含該對象表結構的列屬性的列表['id', 'taskName', 'ifFocus'] tabledata = {"data": []} for obj in objs: row = [None]*len(fields) for field in [x for x in dir(obj) if x in fields]: if field == 'urgentId': data = obj.urgence.urgentName else: data = obj.__getattribute__(field) if data is None: data = '' if data is False: data = 0 if data is True: data = 1 if isinstance(data, datetime.datetime): data = data.strftime('%Y-%m-%d %H:%M') if data == '2099-01-01': data = '時間未定' row[fields.index(field)] = data tabledata["data"].append(row) tabledata = repr(tabledata).replace("'", "\"") # 輸出字符串形式,且以“”作為字符串的頭尾 return tabledata
# 我的任務數據
@task_mgm.route('/taskDataMine', methods=['GET', 'POST'])
@sso_wrapper
def taskinfo_dataMine_fun():
# 應該根據用戶名或ID 的到自己的任務 現在先暫時應任務ID
tasks = Task.query.filter(and_(Task.isDelete != 1, Task.endState != 1)).order_by(Task.urgentGrade.desc()).all()
data = sql3json(tasks, ["id", "taskName", "ifFocus"])
data = data.replace("None", "\" \"")
return data