2014-01-10 52 views
0

我有我需要在表中显示的JSON数据,然后在该表上应用数据表。表格的某些部分是静态的,而其他部分必须动态创建。将会有动态的头文件和offcource数据将被显示在JSON中。我的静态HTML代码如下如何使用JQuery动态创建使用JSON数据的表格

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

但是这个代码不工作,我收到的控制台错误,说: 遗漏的类型错误:无法读取空

的特性“的childNodes”

回答

0

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

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

+0

jqgrid是很多事情的完整解决方案,但是当您只需要使用json填充表时,使用像这样的解决方案可能太重了。还有一些时候,你需要一个不同的json结构,然后预期,然后再次处理json是开销。 –

0

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

我们将不得不删除收盘tr和THEAD和该区域将成为新的代码和它的工作。

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