DataTables - 来自Ajax数据源的动态列?

Cra*_*der 8 php jquery datatables

我试图让DataTables从AJAX数据源读取列名,但似乎必须有一些我必须在这里丢失的东西.

我做了一个小提琴小提琴,我可以手动定义表格使用的数据和列.

该表在HTML中声明,不需要定义列名(<thead>..</thead>):

<table id="example" class="display table table-striped table-bordered" 
       cellspacing="0" width="100%"></table>
Run Code Online (Sandbox Code Playgroud)

在JS中我们手动定义数据:

var data = [
    [ "Row 1 - Field 1", "Row 1 - Field 2", "Row 1 - Field 3" ],
    [ "Row 2 - Field 1", "Row 2 - Field 2", "Row 2 - Field 3" ],
];
Run Code Online (Sandbox Code Playgroud)

然后手动定义列名称或标题:

var columns = [
    { "title":"One" },
    { "title":"Two" }, 
    { "title":"Three" }
];
Run Code Online (Sandbox Code Playgroud)

然后,当我们初始化表时,我们只需将以前声明的信息传递给DataTables使用:

$(document).ready(function() {
  $('#example').DataTable( {
    dom: "Bfrtip",
    data: data,
    columns: columns
  });
});
Run Code Online (Sandbox Code Playgroud)

结果如下:

结果表

现在我的问题是,如果数据包含在AJAX服务器端响应中,我将如何使其工作?

我已经以各种方式和形式尝试了这个,但似乎没有什么似乎在这里工作,我正在努力寻找相关的文件.

例如,如果服务器端处理发回了一个JSON响应,其中包含最后的列名:

{
  "data": [
    {
      "id": "1",
      "One": "Row 1 - Field 1",
      "Two": "Row 1 - Field 2",
      "Three": "Row 1 - Field 3"
    },
    {
      "id": "2",
      "One": "Row 2 - Field 1",
      "Two": "Row 2 - Field 2",
      "Three": "Row 2 - Field 3"
    }
  ],
  "options": [],
  "files": [],
  "columns": [
    {
      "title": "One",
      "data": "One"
    },
    {

      "title": "Two",
      "data": "Two"
    },
    {
      "title": "Three",
      "data": "Three"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

鉴于这是响应,我尝试配置DataTables以使用AJAX数据源来获取行信息,如下所示:

$(document).ready(function() {
  $('#example').DataTable( {
    dom: "Bfrtip",
    "ajax": '/test.php',
    columns: columns
  });
});
Run Code Online (Sandbox Code Playgroud)

但显然columns这里没有定义.

所以我事先得到了列数据:

function getPromise() {
  var deferred = $.Deferred();
  var dataUrl = document.location.origin+'/text.php';
  $.getJSON(dataUrl, function(jsondata) {
    setTimeout(function() {
      deferred.resolve(jsondata);
    }, 0);
  }).fail(function( jqxhr, textStatus, error ) {
    // ********* FAILED
    var err = textStatus + ", " + error;
    console.log( "Request Failed: " + err );
  });
  return deferred.promise();
}
// Get the columns
getPromise().done(function(jsondata) {
  columns = jsondata.columns;
  console.log(columns);
});
Run Code Online (Sandbox Code Playgroud)

并将其传递给DataTables,如上所述.但这次我在运行示例时得到的是控制台中的一个错误TypeError: p is undefined.

那么我怎样才能利用在服务器端响应中返回的动态生成的列?有没有更简单的方法来实现这一目标?

编辑:

DataTables用于服务器端处理的编辑器代码/生成上面提到的JSON响应:

<?php
// DataTables PHP library
require_once '/path/to/DataTables.php';

// Alias Editor classes so they are easy to use
use
  DataTables\Editor,
  DataTables\Editor\Field,
  DataTables\Editor\Format,
  DataTables\Editor\Mjoin,
  DataTables\Editor\Upload,
  DataTables\Editor\Validate;

// Build our Editor instance and process the data coming from _POST
$out = Editor::inst( $db, 'example' )
  ->fields(
    Field::inst( 'id' )->set(false),
    Field::inst( '`One`' )->validator( 'Validate::notEmpty' ),
    Field::inst( '`Two`' )->validator( 'Validate::notEmpty' ),
    Field::inst( '`Three`' )->validator( 'Validate::notEmpty' )
  )
  ->process( $_POST )
  ->data();

// On 'read' remove the DT_RowId property so we can see fully how the `idSrc`
// option works on the client-side.
if ( Editor::action( $_POST ) === Editor::ACTION_READ ) {
    for ( $i=0, $ien=count($out['data']) ; $i<$ien ; $i++ ) {
        unset( $out['data'][$i]['DT_RowId'] );
    }
}

// Create the thead data
if (count ($out) > 0) {
  $columns = array();
  foreach ($out['data'][0] as $column=>$relativeValue) {
    // Add all but the id value
    if ($column !== 'id') {
      // Add this column name
      $columns[] = array(
        "title"=>$column,
        "data"=>$column
      );
    }
  }
}
// Add the the thead data to the ajax response
$out['columns'] = $columns;
// Send the data back to the client
echo json_encode( $out );
Run Code Online (Sandbox Code Playgroud)

ann*_*use 6

如果您不使用内置的DataTables ajax,那么在给定数据结构的情况下应该很容易:

$(document).ready(function() {
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/echo/json/',
        data: {
            json: JSON.stringify(jsonData)
        },
        success: function(d) {
            $('#example').DataTable({
                dom: "Bfrtip",
                data: d.data,
                columns: d.columns
            });
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

就像这个JSFiddle一样,你只能一次加载所有数据,但这不应该是一个大问题...除非你改变它从初始ajax调用获取列,一旦启动DataTable然后添加内置in ajax- 我没试过这个......