循环遍历JSON数组以创建表

时间:2014-01-29 14:29:41

标签: javascript json loops

我有一个JSON数组,我想循环创建一个表。

TITLE等当然是表格的标题和下面的相关数据。

来自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。

4 个答案:

答案 0 :(得分:2)

像这样 - 使用jQuery因为它使Ajax和后续处理变得更加简单 - 请注意,您不必在服务器上解析XML并创建JSON。您可以将XML提供给jQuery并进行类似的处理:

Live Demo

  // 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>")      

我使用的标记是

<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>

答案 1 :(得分:1)

你有一个对象数组,所以循环数组并定位你想要的属性:

for (var i = 0; i < data.length; i++) {
    console.log(data[i].title);
}

要构建表,您必须在循环中构造HTML并追加(快速示例):

table += "<th>" + data[i].title + "</th>";

我会推荐像MustacheJS或Angular这样的模板引擎。

答案 2 :(得分:1)

使用字符串连接从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>'
    );
}

使用此:

var data = [
    {
      "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"
   }
 ]

 build('#mycontainer', data, ['TITLE', 'ARTIST', 'YEAR']);

会导致:

<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>

答案 3 :(得分:0)

我的解决方案是使用普通的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>

然后在我们的JavaScript或JSON文件中,我们有一些数据。我正在创建一个工厂:

var Person = function Person(id, name,age, email, occupation) {
    this.id         = id;
    this.name       = name;
    this.age        = age;
    this.email      = email;
    this.occupation = occupation;
};

然后我将创建数据:

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,因为我相信它更容易看到发生了什么。