jQuery DataTables 在获取服务器数据后设置 aoColumns

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16361732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:00:18  来源:igfitidea点击:

DataTables set aoColumns after getting server data

jquerydatatables

提问by RachelD

I'm using DataTables with server side data to display several tables with details (expanding sub tables). There are two types of sub tables one with three columns one with 7 columns.

我正在使用带有服务器端数据的 DataTables 来显示几个带有详细信息的表(扩展子表)。有两种类型的子表,一种是三列,一种是 7 列。

I would like to set the value of aoColumnsafter I have retrieved data from the server and before the row is displayed but Im having a hard time doing it. Here is what I have so far.

我想aoColumns在从服务器检索数据之后和显示行之前设置 的值,但我很难做到。这是我到目前为止所拥有的。

self.createDataTable = function(identifier, source, rowCallback, initCallback) {
var columnsA = [
        { "mDataProp": "index", "sClass": "index", "bSortable": false },
        { "mDataProp": "text", "sClass": "top-dd", "bSortable": false },
        { "mDataProp": "stats", "sClass": "top-dd stats", "bSortable": false }
    ];
var columnsB = [
        { "mDataProp": "index", "sClass": "index", "bSortable": false },
        { "mDataProp": "check-box", "sClass": "check-box" },
        { "mDataProp": "foundDate", "sClass": "date" },
        { "mDataProp": "pageLink", "sClass": "link" },
        { "mDataProp": "linkText", "sClass": "text" },
        { "mDataProp": "ipAddress", "sClass": "ip" },
        { "mDataProp": "otherLinks", "sClass": "more dd-second-" + thisTR.id }
    ];

$(identifier).dataTable({
    "bPaginate": false,
    "bLengthChange": false,
    "bFilter": false,
    "bSort": true,
    "bInfo": false,
    "bAutoWidth": false,
    "oLanguage": { "sEmptyTable": 'No patterns found' },
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": source,
    "fnServerParams": function(aoData) {
        aoData.push({ "name": "uniqueid", "value": self.uniqueid },
                    { "name": "basedomain", "value": basedomain },
                    { "name": "return_this", "value": $(this).data('returnid') });
    },
    "aoColumns": columnsA,
    "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {                
        return rowCallback(nRow, aData);
    },
    "fnInitComplete": function(oSettings, iStart, iEnd, iMax, iTotal, sPre) {
        initCallback();
    }

});

Basically I would like to catch data from the server, look at a flag passed from the server, set aoColumns and then continue as normal. Any ideas? Im looking through the callback functions http://datatables.net/usage/callbacksbut Im having a hard time setting the columns once Im in a callback.

基本上我想从服务器捕获数据,查看从服务器传递的标志,设置 aoColumns 然后继续正常。有任何想法吗?我正在查看回调函数http://datatables.net/usage/callbacks但一旦我在回调中设置列,我就很难。

I'm also reading the following but Im not getting the desired results.

我也在阅读以下内容,但我没有得到想要的结果。

采纳答案by RachelD

Ok I found a solution though its a little round about. Basically I create a columns variable with all possible columns. I set aoColumnsusing this variable and I also add the variable to my aoDataand send it to the server.

好的,我找到了一个解决方案,虽然它有点绕。基本上,我创建了一个包含所有可能列的列变量。我aoColumns使用此变量进行设置,并将该变量添加到我的aoData并将其发送到服务器。

Here's my server side PHP code:

这是我的服务器端 PHP 代码:

$returnArray = $patternHandler->getGroupsForSection($_GET['return_this']);

if(count($returnArray) > 0) {
    $hiddenCoulumns = array();
    $columns = json_decode($_GET['columns'], true);
    $testRow = $returnArray[0];

    for($i = 0; $i < count($columns); $i++) {
        if(!isset($testRow[$columns[$i]['mDataProp']])) {
            foreach($returnArray AS &$row) {
                $row[$columns[$i]['mDataProp']] = '';
                $hiddenCoulumns[] = $i;
            }
        }
    }
}

echo json_encode(array(
            'sEcho' => intval($_GET['sEcho']),
            'iTotalRecords' => count($returnArray),
            'iTotalDisplayRecords' => count($returnArray),
            'aaData' => $returnArray,
            'hiddenColumns' => $hiddenCoulumns));

You see that I get the $returnArray (my formatted associative array representing data table rows) as normal. Then I loop through my columnsvariable that I passed. If a value for mDataPropisn't in my return array I just add a blank string to make data tables happy.

您会看到我正常获得了 $returnArray(我的格式化关联数组,表示数据表行)。然后我遍历columns我传递的变量。如果一个值 mDataProp不在我的返回数组中,我只需添加一个空白字符串以使数据表满意。

So if I stopped here I would have a bunch of blank columns in each row for my data table. To hide the empty columns I return a array of $hiddenColumns back to the "fnServerData" function which is the callback for the ajax call that gets the data. Here I just loop through my returned hiddenColumns and hide them. The user is none the wiser :)

所以如果我在这里停下来,我的数据表的每一行都会有一堆空白列。为了隐藏空列,我将一组 $hiddenColumns 返回给“fnServerData”函数,该函数是获取数据的 ajax 调用的回调。在这里,我只是遍历返回的 hiddenColumns 并隐藏它们。用户并不聪明:)

Here's my JavaScript:

这是我的 JavaScript:

self.createDataTable = function(identifier, source, rowCallback, initCallback) {
    var columns = [
        { "mDataProp": "index", "sClass": "index", "bSortable": false },
        { "mDataProp": "text", "sClass": "top-dd", "bSortable": false },
        { "mDataProp": "stats", "sClass": "top-dd stats", "bSortable": false },
        { "mDataProp": "check-box", "sClass": "check-box" },
        { "mDataProp": "foundDate", "sClass": "date" },
        { "mDataProp": "pageLink", "sClass": "link" },
        { "mDataProp": "linkText", "sClass": "text" },
        { "mDataProp": "ipAddress", "sClass": "ip" },
        { "mDataProp": "otherLinks", "sClass": "more dd-second-" }
    ];

    var patternsTable = $(identifier).dataTable({
        "bPaginate": false,
        "bLengthChange": false,
        "bFilter": false,
        "bSort": true,
        "bInfo": false,
        "bAutoWidth": false,
        "oLanguage": { "sEmptyTable": 'No patterns found' },
        "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": source,
        "fnServerData": function (sSource, aoData, fnCallback) {
            /* Add some extra data to the sender */
            aoData.push( { "name": "more_data", "value": "my_value" } );
            $.getJSON( sSource, aoData, function (json) { 
                    /* Get server data callback */
                    for(var i = 0; i < json.hiddenColumns.length; i++) {
                        patternsTable.fnSetColumnVis(json.hiddenColumns[i], false);
                    }
                    fnCallback(json)
            } );
        },
        "fnServerParams": function(aoData) {
            aoData.push({ "name": "uniqueid", "value": self.uniqueid },
                        { "name": "basedomain", "value": basedomain },
                        { "name": "return_this", "value": $(this).data('returnid') },
                        { "name": "columns", "value": JSON.stringify(columns)});
        },
        "aoColumns": columns,
        "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {                
            return rowCallback(nRow, aData);
        },
        "fnInitComplete": function(oSettings, iStart, iEnd, iMax, iTotal, sPre) {
            initCallback();
        }

    });
}