这类似于this question,但我想我会改写一些其他字眼,以使自己更加清晰。
我有这个json来自$ .ajax调用:
{“ COLUMNS”:[“ PERSONID”,“ FIRSTNAME”,“ LASTNAME”],“ DATA”:[[1001,“ Scott”,“ Wimmer”],[1002,“ Phillip”,“ Senn”],[1003 ,“ Paul”,“ Nielsen”]]}
问:在JavaScript中,如何解析它以创建一个表,例如:
<table>
<thead>
<tr>
<th>PersonID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1001</td>
<td>Scott</td>
<td>Wimmer</td>
</tr>
<tr>
<td>1002</td>
<td>Phillip</td>
<td>Senn</td>
</tr>
<tr>
<td>1003</td>
<td>Paul</td>
<td>Nielsen</td>
</tr>
</tbody>
</table>
最佳答案
var yourJson = {"COLUMNS":["PERSONID","FIRSTNAME","LASTNAME"],"DATA":[[1001,"Scott","Wimmer"],[1002,"Phillip","Senn"],[1003,"Paul","Nielsen"]];
var table = '<table>';
table += '<thead><tr><th>' + yourJson.COLUMNS.join('</th><th>') + '</th></tr></thead>';
table += '<tbody>';
for (var i=0;i<yourJson.DATA.length;i++) {
table += '<tr><td>' + yourJson.DATA[i].join('</td><td>') + '</td></tr>';
};
table += '</tbody>';
table += '</table>';