DataTables-来自Ajax数据源的动态列? [英] DataTables - Dynamic Columns From Ajax Data Source?

查看:60
本文介绍了DataTables-来自Ajax数据源的动态列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让DataTables从AJAX数据源读取列名,但是似乎这里一定缺少某些东西.

I am trying to get DataTables to read the column names from an AJAX data source but it seems that there must be something that I must be missing here.

我做了一个小提琴小提琴,在其中我可以手动定义要使用的数据和列在桌子旁边.

I made a fiddle fiddle in which I can manually define the data and columns that are being used by the table.

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

The table is declared in the HTML and there is no no need to define the column names (<thead>..</thead>):

<table id="example" class="display table table-striped table-bordered" 
       cellspacing="0" width="100%"></table>

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

In the JS we manually define the data:

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" ],
];

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

Then manually define the column names or titles:

var columns = [
    { "title":"One" },
    { "title":"Two" }, 
    { "title":"Three" }
];

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

Then when we initialise the table we simply pass the previously declared information across for DataTables to use:

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

这将导致:

现在,我的问题是,如果数据包含在 AJAX服务器中,该如何工作?副反应?

Now my question is how would I get this to work if the data is included in the AJAX server side response?

我已经以各种方式和形式尝试了此方法,但是似乎没有任何实际效果,我正在努力寻找与此相关的文档.

I have tried this in various ways and forms but nothing really seems to work out here and I am battling to find relative documentation on this.

例如,如果服务器端处理发回了一个JSON响应,该响应在末尾包含列名称:

For example if the server side processing sent back a JSON response which includes the column names at the end:

{
  "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"
    }
  ]
}

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

Given this is the response, I tried to configure DataTables to use an AJAX data source for the row information as follows:

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

但是显然columns在这里是未定义的.

But obviously columns is undefined here.

所以我先获得了列数据:

So I get the column data before hand:

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);
});

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

And pass it to DataTables as above. But this time all I get when running the example is an error in the console saying TypeError: p is undefined.

那么我该如何利用服务器端响应中返回的动态生成的列呢?有没有更简单的方法来实现这一目标?

So then how could I make use of the dynamically generated columns that are being returned within the server side response? Is there not a simpler way to achieve this?

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

DataTables Editor code for server side processing / to generate the JSON response mentioned above:

<?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 );

推荐答案

如果您不使用内置的DataTables ajax,考虑到数据的结构,这应该足够简单:

If you don't use the built in DataTables ajax it should be easy enough given the structure of your data:

$(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
            });
        }
    });
});

就像此JSFiddle 一样,您只能立即加载所有数据,但是这应该不是一个大问题……除非您对其进行更改,否则请从初始ajax调用中获取列,并在启动DataTable之后再添加内置的ajax-尽管我没有尝试过.

Like this JSFiddle, you're limited then to loading all the data at once but that shouldn't be a huge issue... unless you alter it get the columns from the initial ajax call and once the DataTable is initiated then add the built-in ajax - I've not tried this though...

这篇关于DataTables-来自Ajax数据源的动态列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆