【问题标题】:Datatables.js selected rows not staying selected after ajax.reload()Datatables.js 选择的行在 ajax.reload() 之后没有保持选中状态
【发布时间】:2017-03-14 14:08:29
【问题描述】:

根据says on the tin 的说法,数据表应该能够“在数据重新加载时保留行选择”。但是当使用来自 ajax 的数据时,我无法让它工作。

以下是我制作桌子的方法:

  oTable = $('#fileList').DataTable({
    select: true,
    "ajax": {
      "url": "./data.php",
      "type": "GET"
    },
    rowId: 'Index',
    "createdRow": function (row, data, dataIndex) {
      $(row).addClass(data[2]); //set formatting from data[2]
    }
  });

按照上面参考资料中的说明,我最初使用它每五秒刷新一次表格:

setInterval(function () {
    oTable.ajax.reload();
}

但任何选定的行都会每五秒取消一次选择。所以我尝试更明确:将选定的行加载到数组中并在 setInterval 函数中重新选择它们:

setInterval(function () {
    var selectedRows = [];
    //put all the selected rows into an array:
    sel = oTable.rows('.selected').every(function (rowIdx) {
      selectedRows.push(rowIdx);
    });
    oTable.ajax.reload();
    console.log(selectedRows);
    //select all the rows from the array
    for (var i = 0; i < selectedRows.length; i++) {
      console.log("selecting ",selectedRows[i]);
      oTable.rows(selectedRows[i]).select();
    }
  }, 5000)
});

如果我有一个选定的行(在本例中为第三行),我会在控制台中看到:

Array [ 2 ]
selecting  2    

正如预期的那样,但未重新选择行。如果我在控制台中输入oTable.rows(2).select();,它会选择第三行,但它在setInterval 块中不起作用。

我猜它可能与 rowID 属性有关。我在 HTML 中定义了这样的表:

      <table id="fileList" class="display">
        <thead>
          <tr>
            <th>Index</th>
            <th>Status</th>
            <th>Owner</th>
          </tr>
        </thead>
      </table>

数据来自一个 php 脚本,该脚本返回一个类似的数组

{"data":[["1", "foo", "bar"], ["2", "fuz", "baz"]}

第一项是索引。

【问题讨论】:

    标签: javascript ajax datatables


    【解决方案1】:

    看来问题可能是由于返回的数据中缺少键。您是否尝试过将数据作为关联数组返回,类似于:

    "data": [
        {
            "index": 1,
            "status": "Foo",
            "owner": "Bar"
        }
    ]
    

    然后您可以尝试替换:

    rowId: 'Index',
    

    与:

    rowId: 'index',
    

    【讨论】:

    • 谢谢。请注意,要使用关联数组,您似乎还需要在创建 Datatable 对象时指定列。只是在服务器端更改为关联数组并仍然试图通过其数字索引访问数据导致它中断。
    猜你喜欢
    • 2017-09-17
    • 1970-01-01
    • 2014-06-14
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多