/ Published in: jQuery
Don't know if the code is working, it's written from memory, but I think it will work....
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
<html> <body> <div id="tableHolder"/> </body> <script type="text/javascript"> var tableDef = [ { title: 'Col 1', field: 'field1', render: function(row) { // Notice, how we take data from the row.field1 and row.extra field var d = row.field1 var e = row.extra return e+": "+d } }, { title: 'Col 2', field: 'field2' }, { title: 'Col 3', field: 'field3' } ] // Data is assumed to return something like this: // // [ // {field1: 'row-1, val-1', field2: 'row-1, val-2', field3: 'row-1, val-3', extra: 'extra-1'}, // {field1: 'row-2, val-1', field2: 'row-2, val-2', field3: 'row-2, val-3', extra: 'extra-2'}, // {field1: 'row-3, val-1', field2: 'row-3, val-2', field3: 'row-3, val-3', extra: 'extra-3'}, // ] $.getJSON('${createLink(controller: "mycontroller", action: "myaction", params: "[my:'params']", function(data) { $('#tableHolder').empty() // build table html var table = $('<table><thead/><tbody/></table>') // create the headers from tableDef var tr = $('<tr/>') $.each(tableDef, function(def) { tr.append('<th>'+def.title+'</th>') }) table.find('thead').append(tr) // append data to the table var tbody = table.find('tbody') $.each(data,function(i,d) { tr = $('<tr/>') $.each(tableDef, function(def) { var cell = d[def.field] // Get data by field name definition if(typeof def.render == 'function') { // if it has a render, let the render do its work cell = def.render(d,def.field) } tr.append('<td>'+cell+'</td>') } tbody.append(tr) } $('#tableHolder).append(table) }); </script> </html>