循环遍历JSON数组以创建表 [英] Loop through a JSON array to create a Table
问题描述
我有一个JSON数组,我想循环创建一个表。
I have a JSON array that I would like to loop through to create a table.
TITLE等当然是表的标题和相关数据放在下面。
TITLE etc would of course be the headings of the table and the associated data placed underneath.
来自PHP文件的JSON结果
[
{
"TITLE":"Empire Burlesque",
"ARTIST":"Bob Dylan",
"COUNTRY":"USA",
"COMPANY":"Columbia",
"PRICE":"10.90",
"YEAR":"1985"
},{
"TITLE":"Picture book",
"ARTIST":"Simply Red",
"COUNTRY":"EU",
"COMPANY":"Elektra",
"PRICE":"7.20",
"YEAR":"1985"
}
]
PHP
$filterText = "1985";//$_REQUEST["text"];
$filename = "xml/xml_cd.xml";
$filterHeading = "YEAR";
$filterText = "1985";//$_REQUEST["text"];
$file = simplexml_load_file($filename);
$children = $file->children();
$firstchild = $children[0];
$node = $firstchild->getName();
$result = $file->xpath('//'.$node.'['. $filterHeading . '/text()="'.$filterText.'"]');
$jsondata = json_encode($result,true);
print_r($jsondata);
我认为解决方案应该是javascript,但不能解决如何解决问题,是JSON和JAVASCRIPT的新手。
I believe the solution should be in javascript but can't quite work out how to tackle the problem, being new to JSON and JAVASCRIPT.
推荐答案
像这样 - 使用jQuery因为它使Ajax和后续处理变得更加简单 - 请注意你不必解析服务器上的XML并创建JSON。您可以将XML提供给jQuery并进行类似的处理:
Like this - using jQuery because it makes Ajax and subsequent processing much simpler - please note you do not have to parse the XML on the server and create JSON. You could just serve the XML to the jQuery and have similar processing:
// here is your success from AJAX
var tbody = $("<tbody />"),tr;
$.each(data,function(_,obj) {
tr = $("<tr />");
$.each(obj,function(_,text) {
tr.append("<td>"+text+"</td>")
});
tr.appendTo(tbody);
});
tbody.appendTo("#table1"); // only DOM insertion
如果要指定每个字段:
tr
.append("<td>"+obj.TITLE+"</td>")
.append("<td>"+obj.ARTIST+"</td>")
标记I使用是
<table id="table1">
<thead></thead>
</table>
结果:
<table>
<thead></thead>
<tbody id="table1">
<tr><td>Empire Burlesque</td><td>Bob Dylan</td><td>USA</td><td>Columbia</td><td>10.90</td><td>1985</td></tr>
<tr><td>Picture book</td><td>Simply Red</td><td>EU</td><td>Elektra</td><td>7.20</td><td>1985</td></tr>
</tbody>
</table>
这篇关于循环遍历JSON数组以创建表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!