2017-07-11 42 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