Posted By

sbglasius on 04/01/10


Tagged

jquery json


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

mmcachran


render JSON data to table


 / Published in: jQuery
 

Don't know if the code is working, it's written from memory, but I think it will work....

  1. <html>
  2. <body>
  3. <div id="tableHolder"/>
  4. </body>
  5. <script type="text/javascript">
  6. var tableDef = [
  7. {
  8. title: 'Col 1',
  9. field: 'field1',
  10. render: function(row) {
  11. // Notice, how we take data from the row.field1 and row.extra field
  12. var d = row.field1
  13. var e = row.extra
  14.  
  15. return e+": "+d
  16. }
  17. }, {
  18. title: 'Col 2',
  19. field: 'field2'
  20. }, {
  21. title: 'Col 3',
  22. field: 'field3'
  23. }
  24. ]
  25.  
  26.  
  27. // Data is assumed to return something like this:
  28. //
  29. // [
  30. // {field1: 'row-1, val-1', field2: 'row-1, val-2', field3: 'row-1, val-3', extra: 'extra-1'},
  31. // {field1: 'row-2, val-1', field2: 'row-2, val-2', field3: 'row-2, val-3', extra: 'extra-2'},
  32. // {field1: 'row-3, val-1', field2: 'row-3, val-2', field3: 'row-3, val-3', extra: 'extra-3'},
  33. // ]
  34.  
  35. $.getJSON('${createLink(controller: "mycontroller", action: "myaction", params: "[my:'params']", function(data) {
  36. $('#tableHolder').empty()
  37.  
  38. // build table html
  39. var table = $('<table><thead/><tbody/></table>')
  40.  
  41. // create the headers from tableDef
  42. var tr = $('<tr/>')
  43. $.each(tableDef, function(def) {
  44. tr.append('<th>'+def.title+'</th>')
  45. })
  46. table.find('thead').append(tr)
  47.  
  48. // append data to the table
  49. var tbody = table.find('tbody')
  50.  
  51. $.each(data,function(i,d) {
  52. tr = $('<tr/>')
  53. $.each(tableDef, function(def) {
  54. var cell = d[def.field] // Get data by field name definition
  55.  
  56. if(typeof def.render == 'function') { // if it has a render, let the render do its work
  57. cell = def.render(d,def.field)
  58. }
  59. tr.append('<td>'+cell+'</td>')
  60. }
  61. tbody.append(tr)
  62. }
  63.  
  64. $('#tableHolder).append(table)
  65.  
  66. });
  67. </script>
  68. </html>

Report this snippet  

You need to login to post a comment.