【问题标题】:Set datatables ordering from request url从请求 url 设置数据表排序
【发布时间】:2019-07-02 22:07:00
【问题描述】:

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

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

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

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

我已阅读数据表文档,可以看到如何使用索引值设置顺序,但看不到任何指示如何使用字符串的内容

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

有没有办法可以使用字符串来改变数据的顺序,类似于这个?

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

【问题讨论】:

    标签: datatables


    【解决方案1】:

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

    据我所知,我们不能像 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;
        }
      },
    });
    

    注意事项:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 2021-12-31
      • 2012-05-30
      • 2023-04-03
      • 2013-07-12
      • 2013-04-02
      • 1970-01-01
      相关资源
      最近更新 更多