2016-04-15 42 views
0

我有2個datatables jsfiddle與3 json來源。它works非常好。Datatables - 2個不同的json源碼

但我需要改變這一切json文件:

原文:

{ 
    "data": [{ 
     "id": "11", 
     "cat1": "add1.1", 
     "cat2": "add1.2", 
     "cat3": "add1.3" 
    }, { 
     "id": "12", 
     "cat1": "add2.1", 
     "cat2": "add2.2", 
     "cat3": "add2.3" 
    }] 
} 

新:在頭兩行刪除{"data":和最後}

[{ 
    "id": "11", 
    "cat1": "add1.1", 
    "cat2": "add1.2", 
    "cat3": "add1.3" 
}, { 
    "id": "12", 
    "cat1": "add2.1", 
    "cat2": "add2.2", 
    "cat3": "add2.3" 
}] 

我希望如果jsfiddle刪除.data ,並將"ajax": url更改爲:

"ajax": { 
    "url": url, 
    "dataSrc": "" 
}, 

它會工作。

原文:

$.when(call1, call2).done(function(a1, a2){ 
     var data = a1[0].data; 
     data.splice.apply(data, [2, 0].concat(a2[0].data)); 
     drawTable("#tab1","",data) 
    }); 

drawTable("#tab2","https://api.myjson.com/bins/4lpow","") 

function drawTable(id, url, data) { 
    $(id).dataTable({ 
    "ajax": url, 
    data: data, 
    columnDefs: [ 
     { className: "hide", "targets": [ 0 ] }, 
    ], 
    order: [], 
    ordering: false,   
    columns: [ 
     { "data": "id"}, 
     { "data": "cat1"}, 
     { "data": "cat2"}, 
     { "data": "cat3"} 
    ] 
    }); 
} 

新:

$.when(call1, call2).done(function(a1, a2){ 
     //removed .data 
     var data = a1[0]; 
     //removed .data 
     data.splice.apply(data, [2, 0].concat(a2[0])); 
     drawTable1("#tab11","",data) 
    }); 

drawTable1("#tab21","https://api.myjson.com/bins/3tuls","") 

function drawTable1(id, url, data) { 
     $(id).dataTable({ 
     "ajax": { 
      "url": url, 
      "dataSrc": "" 
     }, 
     data: data, 
     columnDefs: [ 
      { className: "hide", "targets": [ 0 ] }, 
     ], 
     order: [], 
     ordering: false,   
     columns: [ 
      { "data": "id"}, 
      { "data": "cat1"}, 
      { "data": "cat2"}, 
      { "data": "cat3"} 
     ] 
     }); 
    } 

問題是,它與預警工程jsfiddle

請使用POST請求

如果我測試這個file本地警告是:

DataTables warning:table id = tab11 - 無效的JSON響應。有關此錯誤的詳細信息,請參閱http://datatables.net/tn/1

+0

有在的jsfiddle一個語法錯誤,否則你的代碼的工作,看到https://jsfiddle.net/xwp3jhq1/1/ –

+0

是的,看來這個單獨工作。但一起只有警告。我只需要移除警告。也許最好在本地測試[file](https://www.dropbox.com/s/c6suvymg13dmuy8/so.html)。 – jezrael

+1

@Scott波士頓當然,adfed評論和投票刪除。 – jezrael

回答

2

不能在drawTable1功能同時提供ajaxdata選項。

使用下面的代碼來代替:

function drawTable1(id, url, data) { 
    var opt; 
    if (url !== "") { 
     opt = { 
      ajax: { 
       url: url, 
       dataSrc: "" 
      } 
     }; 
    } 
    if (data !== "") { 
     opt = { 
      data: data 
     } 
    } 

    $(id).dataTable($.extend({ 
     columnDefs: [{ 
      className: "hide", 
      targets: [0] 
     }, ], 
     order: [], 
     ordering: false, 
     columns: [ 
      { "data": "id"}, 
      { "data": "cat1"}, 
      { "data": "cat2"}, 
      { "data": "cat3"} 
     ] 
    }, opt)); 
} 
+0

超級,它工作得很好。你也可以提出問題。謝謝。 – jezrael