【问题标题】:How to dynamically create a table using JSON data with jQuery如何通过 jQuery 使用 JSON 数据动态创建表
【发布时间】:2014-01-28 23:16:06
【问题描述】:

我有 JSON 数据,需要在表格中显示,然后在该表格上应用数据表。表的某些部分是静态的,而其他部分必须动态创建。将有动态标题,并且要显示的数据数据将来自 JSON。我的静态 HTML 代码如下

<table border="1" align="center" id="info-table">
<thead>
<tr>
  <th>Roll No</th>
  <th>Student Name</th>
  <th>Student ID</th>
  <th>Class</th>

现在我必须动态添加更多标题,因此我使用 $.each。之后我需要添加 TD 来显示数据。代码如下

obj = $.parseJSON(json.responseText);
    if (obj.collection.response.error) {
        displayError(obj.collection.response.error);
      } else {
          //Prepare fields for Attendance codes
          $.each(obj.collection.response.attendanceCodes, function(key, value){
              $('#info-table tr').append("<th>"+value.title+"</th>");
          });
          //Add the static headers
          $('#info-table tr').append("<th>Teacher Comment</th><th>Admin Comment</th></tr></thead><tbody>");
          //Prepare fields for EachStudent
        $.each(obj.collection.response, function(i, val){
            if(i != 'attendanceCodes'){
                $('#info-table').append("<tr><td>"+val.rollNo+"</td><td>"+val.studentName+"</td><td>"+val.studentId+"</td><td>"+val.className+"</td><td align=\"center\"><div  class=\"radio-green\"><input type=\"radio\" checked=\"checked\" name=\"attend-"+val.studentId+"\" /></div></td><td align=\"center\"><div class=\"radio-red\"><input type=\"radio\"  name=\"attend-"+val.studentId+"\" /></div></td><td><input type=\"text\" style=\"width:200px;\" name=\"teacher-comment-"+val.studentId+"\" /></td><td>- - -</td><td></td><td></td><td></td><td></td></tr>");
            }
        });
        //$('#info-table').dataTable();
        }
    },
    dataType:"JSON"

但此代码不起作用,我在控制台中收到错误消息: 未捕获的类型错误:无法读取 null 的属性“childNodes”

【问题讨论】:

    标签: javascript jquery html json


    【解决方案1】:

    如果你为此使用任何 jquery 插件会更好。比如 datatable 或 jqgrid。它将很好地支持基于 JSON 和 XML 的数据。

    http://trirand.com/blog/jqgrid/jqgrid.html

    【讨论】:

    • jqgrid 是很多事情的完整解决方案,但是当您只需要使用 json 填充表格时,使用这样的解决方案可能太重了。此外,有时您需要与预期不同的 json 结构,然后再次处理 json 是开销。
    【解决方案2】:

    是的,我得到了答案……

    我们将不得不删除关闭的 tr 和 thead 并且该区域的新代码将会生效。

     //Add the static headers
              $('#info-table tr').append("<th>Teacher Comment</th><th>Admin Comment</th>");
    

    【讨论】:

      猜你喜欢
      • 2017-02-18
      • 2019-07-20
      • 2016-04-05
      • 2015-08-15
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多