且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

数据表-动态列

更新时间:2023-12-01 09:56:52

尝试首先获取列,然后继续进行数据表初始化:

Try to get the columns first and then proceed with datatables initialization:

$.getJSON('url/for/colums', function(columnsData) {
   $("#datatable").DataTable({
      ...
      "columns": columnsData
   });
});

编辑

如果我理解正确,您想这样做:

If I understand correctly, you want to do this:

$("#datatable").DataTable({
       "ajax": {
       "url": "http://myjsonurl-that-produces-above-response",
       "dataSrc": "data"
    },
    "columns": getColumns(), //Execute $.getJSON --> asynchronous (the code continous executing without the columns result)
    dom: "Bfrtip",
    "bProcessing": true,
    "bServerSide" : true
});

通过这种方式,当您调用 getColumns()时,执行是异步的,因此列将是未定义的.

In this way, when you call getColumns() the execution is asynchronous, so the columns are going to be undefined.

这就是为什么您必须在getJSON回调函数中调用DataTable初始化程序的原因.

That's why you have to call the DataTable initializer in the getJSON callback function.

另一种方法可能是在非异步函数设置中获取列 async:false (请检查

Another way might be to get the columns in a not asynchronous function setting async: false (Check this question)