【问题标题】:Printing json array in jquery在jquery中打印json数组
【发布时间】:2016-03-13 18:59:28
【问题描述】:

我正在尝试在表格中打印 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

【问题讨论】:

    标签: javascript jquery arrays json


    【解决方案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】:

      我通常会做如下的事情,你可以用你自己的替换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. js 对象键是无序的,每一行可以有不同顺序的列,如果你总是在 json[0] 上迭代,至少你会得到一个一致的顺序,尽管不可预测。 2. 连接文本和 html(如:"&lt;td&gt;" + item[key] + "&lt;/td&gt;")会导致编码问题和注入漏洞。由于问题是关于 jQuery,$('&lt;td&gt;').text(item[key]) 是一个更好的建议,而不是发送一些(更快但有问题的)字符串路径数组。
      【解决方案3】:

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

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

      不仅如此,为每个单元格重复更新页面上的标记简直是糟糕的做法,而且性能非常差。

      【讨论】:

        【解决方案4】:

        您正在为每个 &lt;td&gt; 创建一个新的 &lt;tr&gt;,而键和数据点需要在同一个 &lt;tr&gt;

        添加如下内容:

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

        然后您需要为每组数据点创建一个新的表行以附加到表中,然后遍历数据以创建&lt;td&gt;s。

        【讨论】:

        • Larry Lane 的示例给出了我的意思的完整代码,它应该很容易适应你的情况。
        猜你喜欢
        • 2012-12-05
        • 1970-01-01
        • 2021-08-14
        • 1970-01-01
        • 2011-09-25
        • 2011-10-30
        • 2018-12-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多