如何使用胡子模板在行追加/前缀上修复BS DataTable的UI

时间:2018-10-02 06:08:20

标签: django datatables mustache

使用ajax成功提交后,我正在使用小胡子模板在bs_datatable上添加一行。但是问题是追加后数据表的UI毁了。我尝试使用.draw()重绘数据表,但现在不会出现新添加的行。我究竟做错了什么?还是我必须为此留胡须?

这是我的代码:

html:

<div class="row mt10">
    <div class="col-12">
        <table id="data_table" class="table nowrap table-striped table-bordered">
            <thead>
            <tr role="row">
                <th>Column 1</th>
                <th>Column 2</th>
                <th>Column 3</th>
            </tr>
            </thead>
            <tbody id="data_table_row_cont">
            {% for item in data %}
            <tr role="row">
                <td>{{item.column_1}}</td>
                <td>{{item.column_2}}</td>
                <td>{{item.column_3}}</td>
            </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>
</div>

//mustache template
<script type="text/template" id="mustache_row_content">
    <tr role="row">
        <td>{{item.column_1}}</td>
        <td>{{item.column_2}}</td>
        <td>{{item.column_3}}</td>
    </tr>
</script>

脚本:

datatable = $('#data_table').DataTable({
    responsive: true,
    info: false,
    paging: false,
    scrollCollapse: true,
    "ordering": true,
    searching: false,
});


$("#form").submit(function(e){
    e.preventDefault();

    jQuery.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        success: function(response){

            if(response.success){
                //get mustache template (row template)
                var template = $("#mustache_row_content").html();

                //assigning values to mustache template
                var html = Mustache.to_html(template, {'item': response.data});

                //prepending the row template to datatable's tbody
                $('#data_table_row_cont').prepend(html);

                datatable.draw();
            }
        }
    });
});

0 个答案:

没有答案