如何使用jQuery使用JSON数据动态创建表

时间:2014-01-10 05:07:33

标签: javascript jquery html json

我有JSON数据,我需要在表中显示,然后在该表上应用数据表。表的某些部分是静态的,而其他部分必须是动态创建的。将有动态标头和offcource,要显示的数据数据将从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"

但是这段代码不起作用,我在控制台中遇到错误: 未捕获的TypeError:无法读取null

的属性'childNodes'

2 个答案:

答案 0 :(得分:0)

如果你使用任何jquery插件会更好。像数据表或jqgrid.It将提供对基于JSON和XML的数据的良好支持。

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

答案 1 :(得分:0)

是的,我得到了答案......

我们必须删除结束tr和thead,该区域的新代码将会起作用。

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