设置数据表从请求网址开始的排序

时间:2019-07-02 22:07:00

标签: datatables

我正在尝试找到一种方法,以在请求url或url参数包含某个值时修改数据表的初始顺序。

我正在通过ajax调用数据,类似于以下示例:https://datatables.net/examples/ajax/objects.html

请求可能是https://test.local/officehttps://test.local?col=office

在这种情况下,我希望office按降序对数据表的初始呈现进行排序。

我已经阅读了datatables文档,可以看到如何使用索引值设置顺序,但是看不到任何指示如何使用字符串的信息

$('#example').dataTable( {
    "order": [ 2, 'desc' ]
} );

是否有一种方法可以使用字符串来更改数据的顺序,类似于此?

$('#example').dataTable( {
    "order": [ 'office, 'desc' ]
} );

1 个答案:

答案 0 :(得分:0)

我也在寻找一个命名的列顺序(而不是索引)。

据我所知,我们无法按照this datatable forum上的名称进行订购。

我想出的是:

// Convert url query string to object. I'm using `query-string` library.
// e.g. convert `?order=office&dir=asc` to `{order: 'office', dir: 'asc'}`.
let urlParams = require('query-string').parse(window.location.search);

...


$('#example').DataTable({
  processing: true,
  serverSide: true,
  order: [], // <-- initially empty to avoid defaulting to order: [[0,'asc']].
  columns: [
    ...
    { data: 'office', name: 'office' },
    ...
  ],
  ajax: {
    url: '...', // e.g. url+window.location.search
    data: function (data) {
      // Override the order and dir to be sent to server.
      // Set it to the currently clicked column, or default to what is present in the url parameter.
      let columnName = data.order.length ? data.columns[data.order[0].column].name : urlParams.order; // e.g. 'office'
      let dir = data.order.length ? data.order[0].dir : urlParams.dir;

      // Build the url query params.
      let params = {
        order: columnName, // send the column name 'office' to the server as `?order=office`.
        dir: dir,
        ...
      }

      // Refresh the window.location.search without reloading the browser.
      let urlQueryString = require('query-string').stringify(params);
      window.history.replaceState(null, null, '?'+urlQueryString);

      return params;
    }
  },
});

几件事要注意: