插件 DataTable 创建列表 render参数的详解与如何传递本行数据id

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>&nbsp;<i class="fa fa-times" id="delete">删除</i>&nbsp;<i class="fa fa-star-o" id="focus">关注</i>&nbsp;<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>&nbsp;<i class="fa fa-times" id="delete">删除</i>&nbsp;<i class="fa fa-star-o" id="focus">关注</i>&nbsp;<i class="fa fa-share-square-o" id="share">分享</i>';}
     else {return '<i class="fa fa-edit" id="edit">编辑</i>&nbsp;<i class="fa fa-times" id="delete">删除</i>&nbsp;<i class="fa fa-star" id="focus">已关注</i>&nbsp;<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

  

  

原文地址:https://www.cnblogs.com/We612/p/10143584.html