【问题标题】:CodeIgniter with DataTables ajax populate使用 DataTables ajax 填充 CodeIgniter
【发布时间】:2014-10-15 16:20:38
【问题描述】:

由于DataTable 中有超过 20k~ 项要显示,我想根据一些参数填充它以避免大滞后。

// Clears the DataTable to avoid duplication of items
$('#contacts-table > tbody').empty();
var category_id = 5; // Just for tests

$.post('ajax_getAll', {category_id: category_id}, function(response){

  // I retrieve the 'response' as json_encoded
  var json = JSON.parse(response);

});

如果我不使用DataTables,我会按照传统方式(填充tbody):

$.each(json, function(index, item){

   var tr  = "<tr>";
       tr += "  <td><input type='checkbox' class='checkbox'/></td>";
       tr += "  <td>" + item.id + "</td>";
       tr += "  <td>" + item.name + "</td>";
       tr += "</tr>";

    $('#contacts-table').prepend(tr);
});

但是,使用这段代码,虽然项目已成功检索并插入到 DataTable 中,但 DataTable 的功能(如重新排序、搜索等)停止工作,当我使用这些功能时,它会自动删除我的所有表tbody.

所以我搜索了一下,发现应该使用 Data attribute 填充 DataTable。

// Since I've initialized the DataTable in the load of the jQuery
// I must destroy it so I can re-load it again
$('#contacts-table').DataTable().destroy();

$('#contacts-table').DataTable({
    'bPaginate': true,
    'bLengthChange': false,
    'bFilter': true,
    'bInfo': true,
    'bAutoWidth': true,
    "iDisplayLength": 30,
    'aoColumnDefs': [{
        'bSortable': false,
        'aTargets': ['nosorting']
    }],
    "aaSorting": [],
    'data': json, // Here I'm trying to pass the values without any success
});

使用最后一个代码,我收到此错误Warning: Request unknown

我从 PHP 收到的 json 如下:

[{"id":"16","name":"just testing"}, {"id":"16","name":"stackoverflow"}]

除了我收到的错误之外,我想知道如何使用DataTables by ajax 设置此tr += " &lt;td&gt;&lt;input type='checkbox' class='checkbox'/&gt;&lt;/td&gt;";

【问题讨论】:

    标签: php jquery ajax codeigniter datatable


    【解决方案1】:

    虽然我现在还有其他问题,但我刚刚解决了。

    基本上,我要做的是,除了 dataTable 的设置之外,还要添加一些参数,以便从 PHP 中检索信息作为 json 响应。

    $("#contacts-table").dataTable({
      // All the properties you want...then in the end
     'serverSide': true,
     'ajax': {
                'url': 'ajax_getAll',
                'type': 'POST',
      },
      'columns': [
                  { 'data': 'id' },
                  { 'data': 'name' },
      ]
    });
    

    并且 PHP json 响应必须是这样的:

    $response = array( 'sEcho' => 5,
                       'iTotalRecords' => 5,
                       'iTotalDisplayRecords' => 5,
                       'aaData' => array(array('id' => 1, 'name' => 'stackoverflow'),
                                         array('id' => 2, 'name' => 'google')),
                     ); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 2019-01-15
      • 2013-09-24
      • 1970-01-01
      相关资源
      最近更新 更多