我有一个嵌套的json文件。使用该数据我想创建一个动态的HTML 使用$ .each循环使用jQuery的表。
这里的每一行都是三种语言的类别。 能够使用getJSON方法完成简单的json数据。
[{
"CategoryId": 1,
"CategoryTexts": [{
"LanguageId": 1,
"Description": "Netus.",
"CreatedById": 1
},
{
"LanguageId": 2,
"Description": "Elementum.",
"CreatedById": 2
},
{
"LanguageId": 3,
"Description": "Rhoncus!",
"CreatedById": 3
}
],
"CreatedById": 1,
"IsActive": true
},
{
"CategoryId": 2,
"CategoryTexts": [{
"LanguageId": 1,
"Description": "Aptent!",
"CreatedById": 4
},
{
"LanguageId": 2,
"Description": "Et.",
"CreatedById": 5
},
{
"LanguageId": 3,
"Description": "Pellentesque.",
"CreatedById": 6
}
],
"CreatedById": 2,
"IsActive": true
}
]
表标题为:
<th>Language 1</th>
<th>Language 2</th>
<th>Language 3</th>
答案 0 :(得分:0)
您可以尝试这样的事情:
objJson = JSON.parse(json);
$.each(objJson , function(i, obj) {
$("#myTable tbody").append("<tr><td>" + obj.CategoryTexts[0] + "</td><td class='job'>" + obj.CategoryTexts[1] + "</td><td class='id'>" + obj.CategoryTexts[1] + "</td></tr>");
});
适应您想要的Json对象
答案 1 :(得分:0)
你可以迭代数据..
var data = [{
"CategoryId": 1,
"CategoryTexts": [{
"LanguageId": 1,
"Description": "Netus.",
"CreatedById": 1
},
{
"LanguageId": 2,
"Description": "Elementum.",
"CreatedById": 2
},
{
"LanguageId": 3,
"Description": "Rhoncus!",
"CreatedById": 3
}
],
"CreatedById": 1,
"IsActive": true
},
{
"CategoryId": 2,
"CategoryTexts": [{
"LanguageId": 1,
"Description": "Aptent!",
"CreatedById": 4
},
{
"LanguageId": 2,
"Description": "Et.",
"CreatedById": 5
},
{
"LanguageId": 3,
"Description": "Pellentesque.",
"CreatedById": 6
}
],
"CreatedById": 2,
"IsActive": true
},
{
"CategoryId": 3,
"CategoryTexts": [{
"LanguageId": 1,
"Description": "Metus.",
"CreatedById": 7
},
{
"LanguageId": 2,
"Description": "Quis?",
"CreatedById": 8
},
{
"LanguageId": 3,
"Description": "Rhoncus.",
"CreatedById": 9
}
],
"CreatedById": 3,
"IsActive": true
}
];
var columns = ""
data.forEach(function(e){
var column = '<tr><td>'+e.CategoryTexts[0].Description+'</td><td>'+e.CategoryTexts[1].Description+'</td><td>'+e.CategoryTexts[2].Description+'</td></tr>';
columns+=column;
});
var table = $('<table><tr><th>Language 1</th><th>Language 2</th><th>Language 3</th></tr>'+
columns+'</table>');
$('body').append(table);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>