【问题标题】:jquery datatables - get columns from jsonjquery 数据表 - 从 json 获取列
【发布时间】:2012-01-29 17:18:04
【问题描述】:

在 jquery Datatables 中是否可以使用服务器端脚本定义列? 我需要这样的东西

必须从服务器加载带有日期的列。 那么列数可能会有所不同。

【问题讨论】:

  • 为什么不使用 JSON 获取完整的数据,然后创建一个 HTML 表格,您可以将其展示给用户
  • 我不太明白您所说的“创建 HTML 表格”是什么意思。用 Javascript 创建?
  • 获得 JSON 后,您可以使用 JSON.parse 对其进行解析,然后您可以迭代对象以使用 JQuery 创建 HTML 表
  • 这可以与数据表一起使用吗?现在我用“sAjaxSource”属性加载行。

标签: jquery json datatables


【解决方案1】:

我想我找到了你要找的东西

我将粘贴一些代码 + 发布一个类似 Q' 的链接,您将在其中获得更多信息...

$.ajax( {
    "url": 'whatever.php',
    "success": function ( json ) {
        json.bDestroy = true;
        $('#example').dataTable( json );
     },
    "dataType": "json"
} );

json 是这样的

{

"aaData": [
[ "2010-07-27 10:43:08", "..."], [ "2010-06-28 17:54:33", "..."],
[ "2010-06-28 16:09:06", "..."], [ "2010-06-09 19:15:00", "..."]
] ,

 "aaSorting": [
  [ 1, "desc" ]
 ],

 "aoColumns": [
   { "sTitle": "Title1" },
   { "sTitle": "Title2" }
 ]

}

这里是原帖的链接

Column definition via JSON array (ajax)

【讨论】:

    【解决方案2】:

    扩展 Kamal Deep Singh 所说的内容:

    您可以动态创建表,然后对其应用数据表以获取数据表的功能。

    // up in the html
    <table id="myDatatable" class="... whatever you need..."></table>
    

    然后:

    // in the javascript, where you would ordinarily initialize the datatable
    var newTable = '<thead><tr>'; // start building a new table contents
    
    // then call the data using .ajax()
    $.ajax( {
        url: "http://my.data.source.com",
        data: {}, // data, if any, to send to server
        success: function(data) {
            // below use the first row to grab all the column names and set them in <th>s
            $.each(data[0], function(key, value) {
                newTable += "<th>" + key + "</th>";
            });
            newTable += "</tr></thead><tbody>";                  
    
            // then load the data into the table
            $.each(data, function(key, row) {
                 newTable += "<tr>";
                  $.each(row, function(key, fieldValue) {
                       newTable += "<td>" + fieldValue + "</td>";
                  });
                 newTable += "</tr>";
            });
           newTable += '<tbody>';
    
           $('#myDatatable').html(newTable); // replace the guts of the datatable's table placeholder with the stuff we just created. 
        }
     });
    
     // Now that our table has been created, Datatables-ize it
     $('#myDatatable').dataTable(); 
    

    请注意,您可以像往常一样将设置放入该 .dataTable() 中,但是,不能将 'sAjaxSource' 或任何相关的数据获取函数 - 这是将数据表应用到已经存在的表中,这是我们动态创建的表.

    好的,这是一种很老套的做法,但应该可以。

    目前还没有内置的方法来动态处理数据表。见这里:https://github.com/DataTables/DataTables/issues/273

    【讨论】:

    • 谢谢,但我一直在寻找更方便的方法,类似于这个 "sAjaxSource": "scripts/server_processing.php"
    猜你喜欢
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 2019-01-15
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 2020-11-17
    相关资源
    最近更新 更多