2017-07-11 45 views
1

JSON文件:如何從json數據文件的值中創建JS變量?

[ 
    { 
    "id":"40", 
    "name":"Holliday", 
    "firstname":"Billy", 
    "company":"Blues"} 
] 

我從被填補我的數據表我列一個JSON文件中的一些數據:

$(document).ready(function() { 
      $('#example3').DataTable({ 
       "ajax": { 
       "url": "data.json", 
       "dataSrc": "" 
       }, 
       "columns": [ 
        { "data": "id" }, 
        { "data": "name" }, 
        { "data": "firstname" }, 
        { "data": "company" }, 
        ] 
       }); 
     }); 

現在我需要補充的是結合了文本和ID的自定義列來自json文件。

$(document).ready(function() { 
      $('#example3').DataTable({ 
       "ajax": { 
       "url": "data.json", 
       "dataSrc": "" 
       }, 
       "columns": [ 
        { "data": "id" }, 
        { "data": "name" }, 
        { "data": "firstname" }, 
        { "data": "company" }, 
        {"data":null,className: "action","defaultContent":"The id of this person is" + id} 
        ] 
       }); 
     }); 

所以我需要知道如何定義變量ID以將其放入我的文本。我試過

var id = data.id;

,但它不工作

+0

你的意思是*** 「defaultContent」: 「這個人的ID是」 + data.id ***? – Esko

+0

@Esko是的,其實是的。 – Jarla

+0

沒有看到JSON,沒有人可以幫助你。 plz發佈你的json。 – Khaleel

回答

2

至於其他提到,使用column.render回調,但用它吧:)目標full(或第三個參數)以獲得行完整的JSON項目,並將列data屬性設置爲null

var table = $('#example').DataTable({ 
data: data, 
columns: [ 
    { data: "id", title: 'id' }, 
    { data: "name", title: 'name' }, 
    { data: "firstname", title: 'firstname' }, 
    { data: "company", title: 'company' }, 
    { data: null, 
    title: 'combined', 
    render: function(data, type, full) { 
     return 'The id of '+full.firstname+' '+full.name+' is '+full.id 
    } 
    } 
] 
}) 

演示 - >http://jsfiddle.net/pa1ps1yz/

1

defaultcontent是靜態的,因此不可能訪問數據。

而是嘗試使用呈現

用法:

. 
. 
{ "data": "company" }, 
{ 
    sortable: false, 
    "render": function (data, type, full, meta) {      
    return '<span class="action">The id of this person is '+data.id+'</span>'; 
     } 
} 
+0

經過測試。結果是:''這個人的ID是「+ data.id' – Jarla

+1

@Jarla立即檢查。 –

0
$(document).ready(function() { 
      $('#example3').DataTable({ 
       "ajax": { 
       "url": "data.json", 
       "dataSrc": "" 
        }, 
        "columnDefs": [ 
         { 
        "render": function (data, type, row) { 
         return 'The id of this person is' + data; 
        }, 
        "targets": 4 
        }, 
       ], 
       "columns": [ 
        { "data": "id" }, 
        { "data": "name" }, 
        { "data": "firstname" }, 
        { "data": "company" }, 
        { "data": "id" }, 
        ] 
       }); 
     }); 
+0

這工作! – Jarla