动态获得$ aColumns列名的DataTable arrary(Dynamically get

2019-07-17 17:45发布

首先我会提到什么,我想要的目的。 我使用PHP的笨框架。 我在我的数据库5桌,我想在数据表格式来显示他们在显示页面上点击一个按钮。 我使用的服务器端处理PHP作为数据源。 所以刚开始我做的代码DataTable中格式显示只有一张桌子,是成功的。 现在,我想在按钮点击事件的时间超过了5显示一个表。 但是$ aColumns长度应该等于在HTML表中所定义的列数。 现在考虑痕田部,它有4列student_id数据,exam_id,subject_id和marks_achieved。 现在,另一台是分支,有2个列和branch_id branch_name。 因此,我不能增加或减少HTML标签动态,所以我很困惑。 另外我使用这个源创建数据表。 您可以检查我的getTable()函数在这里。

jQuery的:

$(document).ready(function()
{
$('#datatable').dataTable({
    "sPaginationType":"full_numbers",
    "bJQueryUI":true,
    "bProcessing": true,
    "bServerSide": true,
    "sServerMethod": "GET",
    "sAjaxSource": "datatable/getTable",
    "iDisplayStart": 0,
    "iDisplayLength": 10,
    "aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
    "aaSorting": [[0, 'asc']],
    "aoColumns": [
        { "bVisible": true, "bSearchable": true, "bSortable": true },
        { "bVisible": true, "bSearchable": true, "bSortable": true },
        { "bVisible": true, "bSearchable": true, "bSortable": true },
        { "bVisible": true, "bSearchable": true, "bSortable": true }
        ]
})

$('input[type=button]').bind('click', function(){
        var param = $(this).attr('id');
            data = param + '=1';

        $.ajax({
            type: 'POST',
            url: 'datatable', 
            data: data                
        }).done(function( data ) { 
            console.log(data);
            $('#display_area').html(data); 
        });
    })
    });

HTML:

<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="../js/javascript.js"></script>
<script type="text/javascript" src="../js/jquery.dataTables.min.js"></script>
</head>
<body id="dt_example">
<form action="" method="post">
<input type="button" id="display_branch" name="display_branch" value="Display Branch Table" >
<input type="button" id="display_marks" name="display_marks" value="Display Marks Table" >
</form>   
<div id="container">
<div id="demo">
<table id="datatable" cellpadding="0" cellspacing="0" border="0" width="100%">
<thead>
    <tr>
        <th>Student ID</th>
        <th>Exam ID</th>
        <th>Subject ID</th>
        <th>Marks Achieved</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</tbody>
<tfoot></tfoot>
</table>
</div>
<div class="spacer"></div>
</div>
</body>
</html>

为了得到列动态我做了这些改变如下面的datatable.php,但它无法正常工作。 这里有什么错误,或者我应该尝试一些其他的办法?

   if(isset($_POST['display_marks']))
    {
        $aColumns = array('student_id', 'exam_id', 'subject_id', 'marks_achieved');
        $sTable = 'marks';
    }
    if(isset($_POST['display_branch']))
    {
        $aColumns = array('branch_id', 'branch_name');
        $sTable = 'branch';
    }

编辑:发表user1190992作品的解决方案,但整个方法发生变化。 而在这我要消毒列的标题。 “branch_id”显示,而不是我想要显示分行ID。 我怎样才能执行此消毒?

Answer 1:

这是动态创建从JSON数据HTML一个非常简单的方法。 它不虽然使用服务器端处理。

JavaScript的

$(document).ready(function() {
    $(".abutton").click(function() {
        $('#myDatatable_wrapper').detach(); //Remove existing table
        var table = '<table id="myDatatable" class="table"><thead><tr>';
        $.ajax({
            url: 'dt.php',
            data: "table_id="+$(this).attr("id"),
            type: "POST",
            success: function (data) {
                $.each(data.aoColumns, function(key, value) {
                    table += "<th>"+value+"</th>";
                });
                table += "</tr></thead><tbody>";
                $.each(data.aaData, function(key, row) {
                    table += "<tr>";
                    $.each(row, function(key, fieldValue) {
                        table += "<td>"+fieldValue+"</td>";
                    });
                    table += "</tr>";
                });
                table += '<tbody></table>';
                $('.container').html(table);
                $('#myDatatable').dataTable();
            },
            dataType: "json"
        });
    });
});

PHP

$table_id = filter_input(INPUT_POST, "table_id", FILTER_SANITIZE_STRING);
$dbconn = mysqli_connect("localhost", "username", "password");

if($table_id == "table1") {
    $sql_query = mysqli_query($dbconn, 'SELECT * FROM display_branch');
}
else {
    $sql_query = mysqli_query($dbconn, 'SELECT * FROM display_marks');
}

if(mysqli_num_rows($sql_query) == 0) {
    echo "Check your ID";
    exit(1);
}
$data = array();
$data['aaData'] = array();
while($row = mysqli_fetch_assoc($sql_query)) {
    $data['aaData'][] = $row;
}

$data['aoColumns'] = array();
while($finfo = mysqli_fetch_field($sql_query)) {
    $data['aoColumns'][] = $finfo->name;
}
echo json_encode($data);

HTML

<button id="table1" class="abutton">Table 1</button><br /><button id="table2" class="abutton">Table 2</button>
<div class="container"></div>

希望这可以帮助。



文章来源: Dynamically get column names in $aColumns arrary in datatables