在jquery中打印json数组

时间:2016-03-13 18:59:28

标签: javascript jquery arrays json

我正在尝试在表格中打印JSON数组。这是我的代码。有什么建议?提前谢谢。

[
  {
    "id": 1,
    "name": "name1",
    "age": 10,
    "feedback": "feedback1"
  },
  {
    "id": 2,
    "name": "name2",
    "age": 90,
    "feedback": "feedback2"
  },
  {
    "id": 3,
    "name": "name3",
    "age": 30,
    "feedback": "feedback3"
  },
  {
    "id": 4,
    "name": "name4",
    "age": 50,
    "feedback": "feedback4"
  }
]

var fileName = "";

function GridLibrary(fileName) {
  this.fileName = fileName;

}
GridLibrary.prototype = {
  set_fileName: function(fileName) {
    this.fileName = fileName;
  },
  get_fileName: function() {
    return this.fileName;
  }
};

GridLibrary.prototype.display = function() {
  $.ajax({

    url: this.get_fileName(),
    error: function(that, e) {

      console.log(e);
    },
    success: function(data) {
      // printing the keys
      var Mytable = "<table>";
      $.each(data[0], function(key, value) {
        $('body').append('<tr><td id="div' + key + '" </td></tr>');
        $('#div' + key).append(key);
      });
      // printing the rest
      $.each(data, function(index, MyList) {
        $.each(MyList, function(key, value) {
          $('#div' + key).append(" " + MyList[key] + " ");
        });
      });
      Mytable += '</table>';
      $('body').append(Mytable);
    }
  });
};

输出

 id 1 2 3 4
name name1 name2 name3 name4
age 10 90 30 50
feedback feedback1 feedback2 feedback3 feedback4

但我希望它像

id  name  age  feedback
 1  name1  10  feedback1
 2  name2  90  feedback2
 3  name3  30  feedback3
 4  nanme4  50  feedback4

4 个答案:

答案 0 :(得分:1)

我通常会执行以下操作,您只需用自己的代码替换json数组:

Live Example

<强> HTML:

<h2>An Example of Turning an Array of Objects into a Html Table</h2>

<div id="left">&nbsp;</div>
<div id="results"></div>
<div id="right">&nbsp;</div>

<强> CSS(可选):

body {
  background: gray;
}

#results,
#left,
#right {
  float: left;
}

#left {
  width: 33.33%;
}

#right {
  width: 33.3%;
}

#results {
  width: 33.33%;
}

h2{
  font-family:georgia;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  background-color: teal;
  color: #f0ffff;
}

td,
th {
  border: black solid 1px;
  padding: 5px;
}

td {
  background-color: teal;
  color: white;
}

th {
  background-color: blue;
  color: white;
  font-family: georgia;
}

<强> JavaScript的:

var json = [{

  "firstname": "Larry",
  "lastname": "Lane",
  "phone1": "111-111-1111"

}, {
  "firstname": "Gypsy",
  "lastname": "Lane",
  "phone1": "111-111-1111"

}];

//array to hold the html for the table
var html = [];

//add the opening table and tablebody tags
html.push("<table>\n<tbody>");


//begin adding the table headers

html.push("<tr>");

//loop through the property names of the first object
for(var propertyNames in json[0]){//begin for in loop

  html.push("<th>" + propertyNames  + "</td>");

}//end for in loop

html.push("</tr>");

//loop through the array of objects
json.forEach(function(item) { //begin forEach

  //add the opening table row tag
  html.push("<tr>");

  //loop though each of the objects properties
  for (var key in item) { //begin for in loop

    //append the table data containing the objects property value
    html.push("<td>" + item[key] + "</td>");

  } //end for in loop

  //add the closing table row tag
  html.push("</tr>");

}); //end forEach

//add the closing table and table body tags
html.push("<table>\n</tbody>");

//testing display of results
document.getElementById("results").innerHTML = html.join("");

答案 1 :(得分:1)

你可以尝试一下:

var table = [{
  "id": 1,
  "name": "name1",
  "age": 10,
  "feedback": "feedback1"
}, {
  "id": 2,
  "name": "name2",
  "age": 90,
  "feedback": "feedback2"
}, {
  "id": 3,
  "name": "name3",
  "age": 30,
  "feedback": "feedback3"
}, {
  "id": 4,
  "name": "name4",
  "age": 50,
  "feedback": "feedback4"
}];

function addTable(tableData) {

  var table = $('<table>');

  var tableHeading = $('<tr>');


  for (var title in tableData[0]){
    if (! tableData[0].hasOwnProperty(title))
        continue;

    var headingColumn = $('<th>'+ title +'</th>');
    headingColumn.appendTo(tableHeading);
  }

  tableHeading.appendTo(table);

  tableData.forEach((rowData)=>{

    var row  = $('<tr>');

    for (var columnData in rowData) {
      if (! rowData.hasOwnProperty(columnData))
        continue;

      var column = $('<td>' + rowData[columnData] + '</td>');

      column.appendTo(row);
    }

    row.appendTo(table);

  });

  table.appendTo('body');
}

addTable(table);

小提琴:https://jsfiddle.net/41g8g9Lc/1/

请注意,这不会检查以确保每行中的列数相同。如果需要,可以添加这种处理。

答案 2 :(得分:0)

您为每个<tr>创建一个新的<td>,而密钥和数据点需要位于同一个<tr>

添加如下内容:

   $('body').append('<tr id="keys"></tr>');
   $('body tr.keys').append('<td id="div' + key + '" </td>');

然后您需要为每组数据点创建一个新表行以附加到表中,然后遍历数据以创建<td>

答案 3 :(得分:0)

您使用两种不同的方法输出标记。

如果您要使用字符串连接,请将其用于整个表。关键是,在创建行和单元格之后,您将附加<table></table>正文

不仅如此,而且反复更新页面上每个单元格的标记只是做法不好而且非常不具备性能。