我知道以前有人问过这个问题,但我的变体与其他答案不匹配。
我有一个json数据源,格式如下:
{
"columns":[
{"title":"Store Number","data":"StoreNbr"},
{"title":"Store Name","data":"StoreName"},
{"title":"2016-01-01","data":"2016-01-01"},
{"title":"2016-01-02","data":"2016-01-02"}
],
"data":[
{"2016-01-01":"51","StoreNbr":"1","StoreName":"Store 1","2016-01-02":"52"}
]
}我像这样加载数据:
$("#datatable").DataTable({
"ajax": {
"url": "http://myjsonurl-that-produces-above-response",
"dataSrc": "data"
},
"columns": [
{"title":"Store Number","data":"StoreNbr"},
{"title":"Store Name","data":"StoreName"},
{"title":"2016-01-01","data":"2016-01-01"},
{"title":"2016-01-02","data":"2016-01-02"},
],
dom: "Bfrtip",
"bProcessing": true,
"bServerSide" : true
});上面的工作是完美的。我需要的是动态加载列,如下所示:
"columns": $.getJSON($('#datatable').DataTable().ajax.url(),
function(json){
return (JSON.stringify(json.columns));
});我得到的只是一个aDataSource错误。如果我在代码中的其他地方运行.getJSON,我会得到预期的响应,也就是我需要的响应。有什么想法吗?
我想让它更好地工作,因为我的数据源根据我应用的影响json源、数据集等的过滤器而不断变化。
更新:
表的初始化方式:
<script type="text/javascript">
TableManageButtons.init();
TableManageButtons = function () {"use strict"; return { init: function () { handleDataTableButtons() } }}();
var handleDataTableButtons = function () {
"use strict";
0 !== $("#datatable-buttons").length && $("#datatable-buttons").DataTable({
"ajax": {
"url": "http://myjsonurl.php",
.......发布于 2016-05-06 19:11:26
尝试先获取列,然后继续执行datatables初始化:
$.getJSON('url/for/colums', function(columnsData) {
$("#datatable").DataTable({
...
"columns": columnsData
});
});编辑
如果我没理解错的话,你想这样做:
$("#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()时,执行是异步的,因此列将是未定义的。
这就是为什么必须在getJSON回调函数中调用DataTable初始化器的原因。
另一种方法可能是获取非异步函数设置async: false (检查this question)中的列
发布于 2016-05-06 19:12:15
你可以形成一个自定义的js函数,一旦你从服务器得到响应,就把你的头放到合适的地方。看看下面的代码:
来自服务器的JSON响应:
{
"columns": [
[ "Name" ],
[ "Position" ],
[ "Office" ],
[ "Extn." ],
[ "Start date" ],
[ "Salary" ]
],
"data": [
[
"Tiger Nixon",
"System Architect",
"Edinburgh",
"5421",
"2011/04/25",
"$320,800"
],....
}并使用js方法对其进行处理,以将标头放在适当的位置:
$( document ).ready( function( $ ) {
$.ajax({
"url": 'arrays_short.txt',
"success": function(json) {
var tableHeaders;
$.each(json.columns, function(i, val){
tableHeaders += "<th>" + val + "</th>";
});
$("#tableDiv").empty();
$("#tableDiv").append('<table id="displayTable" class="display" cellspacing="0" width="100%"><thead><tr>' + tableHeaders + '</tr></thead></table>');
//$("#tableDiv").find("table thead tr").append(tableHeaders);
$('#displayTable').dataTable(json);
},
"dataType": "json"
});
});有关详细说明,请查看此。希望这能有所帮助!!
https://stackoverflow.com/questions/37070552
复制相似问题