Javascript 循环通过JSON数组创建表
我有一个JSON数组,我想通过它来循环创建一个表 标题等当然是表格的标题和放在下面的相关数据 来自PHP文件的JSON结果Javascript 循环通过JSON数组创建表,javascript,json,loops,Javascript,Json,Loops,我有一个JSON数组,我想通过它来循环创建一个表 标题等当然是表格的标题和放在下面的相关数据 来自PHP文件的JSON结果 [ { "TITLE":"Empire Burlesque", "ARTIST":"Bob Dylan", "COUNTRY":"USA", "COMPANY":"Columbia", "PRICE":"10.90", "YEAR":"1985" },{ "TITLE":"Picture book
[
{
"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,因此无法解决该问题。您有一个对象数组,因此请循环该数组并针对您想要的属性:
for (var i = 0; i < data.length; i++) {
console.log(data[i].title);
}
for(变量i=0;i
要构建表,必须在循环中构造HTML并在其后追加(快速示例):
table+=“”+数据[i].标题+“”;
我建议使用MustacheJS或Angular之类的模板引擎。您有一个对象数组,因此循环该数组并针对您想要的属性:
for (var i = 0; i < data.length; i++) {
console.log(data[i].title);
}
for(变量i=0;i
要构建表,必须在循环中构造HTML并在其后追加(快速示例):
table+=“”+数据[i].标题+“”;
我建议使用MustacheJS或Angular之类的模板引擎。像这样使用jQuery,因为它使Ajax和后续处理更加简单。请注意,您不必在服务器上解析XML并创建JSON。您可以将XML提供给jQuery并进行类似的处理:
// 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
像这样-使用jQuery,因为它使Ajax和后续处理更加简单-请注意,您不必在服务器上解析XML并创建JSON。您可以将XML提供给jQuery并进行类似的处理:
// 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
使用字符串连接从JSON构建表:
function build(target, data, columns) {
var head = '', rows = '';
for (int j = 0; j < columns.length; j++) {
var cols = '';
for (int i = 0; i < data.length; i++) {
cols += '<td>'+data[i][columns[j]]+'</td>';
}
head += '<th>'+columns[j]+'</th>';
rows += '<tr>'+cols+'</tr>';
}
$(target).html(
'<table>'+
'<thead>'+head+'</thead>'+
'<tbody>'+rows+'</tbody>'+
'</table>'
);
}
将导致:
<div id="mycontainer">
<table>
<thead>
<th>TITLE</th>
<th>ARTIST</th>
<th>YEAR</th>
</thead>
<tbody>
<tr>
<td>Empire Burlesque</td>
<td>Bob Dylan</td>
<td>1985</td>
</tr>
<tr>
<td>Picture book</td>
<td>Simply Red</td>
<td>1985</td>
</tr>
</tbody>
</table>
</div>
标题
艺术家
年
皇帝讽刺剧
鲍勃·迪伦
1985
图画书
纯红色
1985
使用字符串连接从JSON构建表:
function build(target, data, columns) {
var head = '', rows = '';
for (int j = 0; j < columns.length; j++) {
var cols = '';
for (int i = 0; i < data.length; i++) {
cols += '<td>'+data[i][columns[j]]+'</td>';
}
head += '<th>'+columns[j]+'</th>';
rows += '<tr>'+cols+'</tr>';
}
$(target).html(
'<table>'+
'<thead>'+head+'</thead>'+
'<tbody>'+rows+'</tbody>'+
'</table>'
);
}
将导致:
<div id="mycontainer">
<table>
<thead>
<th>TITLE</th>
<th>ARTIST</th>
<th>YEAR</th>
</thead>
<tbody>
<tr>
<td>Empire Burlesque</td>
<td>Bob Dylan</td>
<td>1985</td>
</tr>
<tr>
<td>Picture book</td>
<td>Simply Red</td>
<td>1985</td>
</tr>
</tbody>
</table>
</div>
标题
艺术家
年
皇帝讽刺剧
鲍勃·迪伦
1985
图画书
纯红色
1985
我的解决方案是使用普通的旧JavaScript。
为了方便起见,我在HTML中添加了一些表元素,而不是全部从JS创建
<table id="people" class='table table-striped'>
<thead>
<th>id</th>
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Occupation</th>
</thead>
<tbody></tbody>
</table>
然后我将创建数据:
var data = [
new Person( 1,'Bill Thompson' , 45,'bill@example.com' , 'Math Teacher' ),
new Person( 2,'Lori Segway' , 22,'lori@example.com' , 'Hair Stylist' ),
new Person( 3, 'Peggy Stiller' , 31, 'peg@example.com' , 'Makeup Artist' ),
new Person( 4, 'Harry Lane' , 62, 'harry@example.com', 'Company Ceo' ),
new Person( 5, 'Michael Lowney', 40, 'mike@example.com' , 'Gung Fu Instructor' ),
new Person( 6,'Paul Byrant' , 56, 'paul@example.com' , 'Web Developer' )
];
按如下方式获取DOM元素:
var output=document.querySelector(“#people tbody”)
并使用forEach循环填充表
data.forEach(function (person) {
var row = document.createElement('tr');
['id', 'name', 'age', 'email', 'occupation'].forEach(function (prop) {
var td = document.createElement('td');
td.appendChild(document.createTextNode(person[prop]));
row.appendChild(td);
});
output.appendChild(row);
});
就这么简单。我使用forEach是因为我相信它更容易看到正在发生的事情。我的解决方案是使用简单的旧JavaScript。 为了方便起见,我在HTML中添加了一些表元素,而不是全部从JS创建
<table id="people" class='table table-striped'>
<thead>
<th>id</th>
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Occupation</th>
</thead>
<tbody></tbody>
</table>
然后我将创建数据:
var data = [
new Person( 1,'Bill Thompson' , 45,'bill@example.com' , 'Math Teacher' ),
new Person( 2,'Lori Segway' , 22,'lori@example.com' , 'Hair Stylist' ),
new Person( 3, 'Peggy Stiller' , 31, 'peg@example.com' , 'Makeup Artist' ),
new Person( 4, 'Harry Lane' , 62, 'harry@example.com', 'Company Ceo' ),
new Person( 5, 'Michael Lowney', 40, 'mike@example.com' , 'Gung Fu Instructor' ),
new Person( 6,'Paul Byrant' , 56, 'paul@example.com' , 'Web Developer' )
];
按如下方式获取DOM元素:
var output=document.querySelector(“#people tbody”)
并使用forEach循环填充表
data.forEach(function (person) {
var row = document.createElement('tr');
['id', 'name', 'age', 'email', 'occupation'].forEach(function (prop) {
var td = document.createElement('td');
td.appendChild(document.createTextNode(person[prop]));
row.appendChild(td);
});
output.appendChild(row);
});
就这么简单。我之所以使用forEach,是因为我相信它更容易看到正在发生的事情。有没有一种方法可以在不特别调用标题的情况下执行循环?(.TITLE等)不,每次JSON文件更改时,您都必须重新加载。如果您想要实时更改,则需要web Socketsy您可以将循环放入一个函数中,并为数组设置一个参数,为属性名称设置一个参数:
var myprop='TITLE';对于{…data[i][myprop]…}
并且您每次调用函数时都会更改该参数。顺便说一句,这个解决方案是IMO最快的(使用字符串连接而不是DOM的多个附件)。有没有一种方法可以在不专门调用头的情况下执行循环?(.TITLE等)不,每次JSON文件更改时,您都必须重新加载。如果您想要实时更改,则需要web Socketsy您可以将循环放入一个函数中,并为数组设置一个参数,为属性名称设置一个参数:var myprop='TITLE';对于{…data[i][myprop]…}
并且您每次调用函数时都会更改该参数。顺便说一句,此解决方案是IMO中最快的(使用字符串连接而不是DOM的多个附件)。是否有方法在不指定.TITLE/.ARTIST的情况下循环对象?因为使用中的JSON文件随时都可能更改。如果您有大量数据,那么最好进行字符串连接,而不是在每个循环上附加到dom。您只需在for-loop之后向表追加一次。如何检查键是否存在?以便以后可以使用默认值替换它。例如:如果(key.length==0){key=“-”}
.append(“+(obj.TITLE | |“-”)+”)
@mplungjan您会在我的示例中实现吗?有没有一种方法可以在不指定.TITLE/.ARTIST的情况下循环对象?因为使用中的JSON文件随时都可能更改。如果您有大量数据,那么最好进行字符串连接,而不是在每个循环上附加到dom。您只需在for-loop之后向表追加一次。如何检查键是否存在?以便以后可以使用默认值替换它。例如:如果(key.length==0){key=“-”}
.append(“+(obj.TITLE | |“-”)+”)
@mplungjan您会在我的示例中实现吗?