使用ajaxURI的 Tabulator实例未显示任何数据

前端开发 2026-07-08

我刚接触Tabulator库。在通过AJAX加载数据时遇到了问题。之前在另一个视图中使用(基于CodeIgniter 4框架)时是可以工作的。但我不清楚为何在这种情况下连工作都做不到。我确认该URL的返回结果是:

[ { "key1": "value1", ... } ]

唯一的区别是字段名key1的首字母大写,例如Key1。我尝试对ajaxResponse进行调试,但控制台没有任何输出。下面是用于初始化Tabulator的 JavaScript代码。

<script>

  document.addEventListener('DOMContentLoaded', () => {

    var table = new Tabulator('#interfaces-table', {
      ajaxURL: '<?= url_to('url'); ?>',
      ajaxConfig: 'POST',
      autoColumns: true,
      ajaxResponse: function(url, params, response) {
        //url - the URL of the request
        //params - the parameters passed with the request
        //response - the JSON object returned in the body of the response.
        console.log(response)

        return response.tableData; //return the tableData property of a response json object
      },
      layout: 'fitColumns',
      pagination: true,
      paginationSize: 10,
      paginationSizeSelector: [10, 25, 50, 100],
      movableColumns: true,
    });

    var url = table.getAjaxUrl();

    console.log(url)
  });
</script>

如果能得到帮助,将不胜感激,谢谢!。

解决方案

字段名首字母大写并不是问题。Tabulator可以使用像 "Key1" 这样的字段。

主要问题在这里:

return response.tableData;

但你的响应是:

[
  { "Key1": "value1" }
]

这意味着 response 已经是一个数组。它没有一个 tableData 属性,所以 response.tableData 返回 undefined。Tabulator期望AJAX数据是一个行对象的数组,或者 ajaxResponse 必须返回一个行对象数组。

请使用以下:

<script>
  document.addEventListener('DOMContentLoaded', () => {
    var table = new Tabulator('#interfaces-table', {
      ajaxURL: '<?= url_to('url'); ?>',
      ajaxConfig: 'POST',
      autoColumns: true,

      ajaxResponse: function(url, params, response) {
        console.log("AJAX response:", response);
        return response;
      },

      layout: 'fitColumns',
      pagination: true,
      paginationSize: 10,
      paginationSizeSelector: [10, 25, 50, 100],
      movableColumns: true,
    });

    console.log(table.getAjaxUrl());
  });
</script>

或者完全移除 ajaxResponse

var table = new Tabulator('#interfaces-table', {
  ajaxURL: '<?= url_to('url'); ?>',
  ajaxConfig: 'POST',
  autoColumns: true,
  layout: 'fitColumns',
  pagination: true,
  paginationSize: 10,
  paginationSizeSelector: [10, 25, 50, 100],
  movableColumns: true,
});

ajaxResponse 仅在服务器返回如下包装数据时才需要:

{
  "tableData": [
    { "Key1": "value1" }
  ]
}

在这种情况下,这将是正确的:

ajaxResponse: function(url, params, response) {
  return response.tableData;
}

还有一点要强调:如果 console.log(response)ajaxResponse 里面从未执行,那么在Tabulator到达 ajaxResponse 之前,AJAX请求很可能已经失败。请检查浏览器开发者工具的Network标签并验证:

Status: 200
Response Content-Type: application/json
Response body: valid JSON array

对于CodeIgniter 4,请返回如下JSON:

return $this->response->setJSON([
    ['Key1' => 'value1']
]);

同时确保在脚本运行前,表格所在的div已存在:

<div id="interfaces-table"></div>

因此,直接的修复方法是:

return response;

不是:

return response.tableData;
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章