【问题标题】:How do I use the async .update() method for DataTables in MDBootstrap?如何在 MDBootstrap 中为 DataTables 使用异步 .update() 方法?
【发布时间】:2021-07-12 08:06:03
【问题描述】:

我是 MDBootstrap 的新手,我正在尝试学习如何使用 DataTables。我在他们的网站上看到了异步表更新的示例,但是我发现将其转换为我的用例会让人感到困惑。

我有兴趣学习如何使用异步表更新方法,因为我希望我的表根据从下拉列表中收集的过滤器动态更新四列。

我希望表格通过调用 PHP 端点来获取其数据,该端点将以 JSON 形式返回数据,但我不明白如何使用 asyncTable.update() 方法(基于他们的示例)。

为简单起见,我们假设 PHP 端点返回的 JSON 类似于:

[ { "a": "a string", "b": "another string", "c": "another string", "d": "another string" }, { "a": "a string", "b": "another string", "c": "another string", "d": "another string" }]

基于来自 MDBootstrap 站点(如下所列)的示例代码 sn-p,如何修改代码以调用我自己的端点?我不明白示例代码的 .update() 方法中的 javascript 语法:

const columns = [
  { label: 'A', field: 'a' },
  { label: 'B', field: 'b' },
  { label: 'C', field: 'c' },
  { label: 'D', field: 'd' },
];

const asyncTable = new mdb.Datatable(
  document.getElementById('datatable'),
  {
    columns,
  }
);

//var url = 'MY OWN PHP ENDPOINT URL';
var url = 'https://jsonplaceholder.typicode.com/users';
fetch(url)
  .then((response) => response.json())
  .then((data) => {
    asyncTable.update(
      {
        rows: data.map((user) => ({
          ...user,
          address: `${user.address.city}, ${user.address.street}`,
          company: user.company.name,
        })),
      },
      { loading: false }
    );
  });
});

对于如何使用我自己的端点而不是提供的示例端点和数据结构来使用此方法的任何帮助,我将不胜感激。

谢谢

【问题讨论】:

    标签: javascript json twitter-bootstrap bootstrap-5 mdbootstrap


    【解决方案1】:

    您必须在fetch 中更改端点 URL 的链接

      fetch('https://custom-api.com/rows')
    

    update() 方法有两个参数:dataoptions。更改 URL 后,您必须修改 data 参数以对应您的数据。在您的示例中,它将如下所示:

       fetch('https://your-url.com/rows')
      .then((response) => response.json())
      .then((data) => {
        asyncTable.update(
          {
            rows: data.map((row) => ({
              a: row.a,
              b: row.b,
              c: row.c,
              d: row.d
            })),
          },
          { loading: false }
        );
      });
    

    这个例子对你来说可能看起来更简洁:https://mdbootstrap.com/snippets/standard/m-duszak/3000204#js-tab-view

    【讨论】:

      猜你喜欢
      • 2017-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      • 2017-03-06
      相关资源
      最近更新 更多