3

I am still new to JSON/jQuery.

I need some quick guidance on how to dynamically populate Html table on the client. My table has fixed columns, but rows grow dynamically depending on data retreived.

Say I have a Web Method on the server (GetActiveUsers) that is returning, say n- users. I am using this sql:

select userId, Title,Surname,FirstName from Users where status=1

Please give me sample code

Edit

I have solution for this on this post here Thanks guys

Community
  • 1
  • 1
Julius A
  • 38,062
  • 26
  • 74
  • 96

1 Answers1

3

This is a perfect application of jQote THE jQuery javascript templating engine. You can fetch it from here: http://aefxx.com/jquery-plugin/jqote.

As an example consider the following:

// Example of your json data ... an array of user objects
[{
    "Title": "Dr.",
    "Surname": "House",
    "Firstname": "Geronimo"
  },
  {
    "Title": "Mr.",
    "Surname": "Franklin",
    "Firstname": "Benjamin"
  }
]

Now here's the template you would define in your HTML (or whatever output file you have):

<script type="text/html" id="template">
    <![CDATA[
        <tr>
            <td class="no"><%= j+1 %></td>
            <td class="title"><%= this.Title %></td>
            <td class="user"><%= this.Firstname + " " + this.Surname %></td>
        </tr>
    ]]>
</script>

So, we're almost done. Let's define our containing table and call jQote on the json data to magically fill the table.

... your markup ...

<table id="users"></table>

... more markup ...

<script type="text/javascript">
    var jsondata = xxx // get your data somehow

    // Now call jQote on the template providing your json data
    $('#template').jqote(jsondata).appendTo($('#users'));
</script>

That's all (well it's just the beginning, jQote is way more powerfull than I could tell you here).

Hope you like it, give it a try.

BTW: The use of as your template's container is perfectly legal markup. And browsers will not display it in any case.

Mickael Lherminez
  • 679
  • 1
  • 10
  • 29
aefxx
  • 24,835
  • 6
  • 45
  • 55
  • Took me a while to work out how to use json from an ajax call to feed jqote. Here's (one) way: var jsondata = $.getJSON('/path/to/call/', function(data) { row = $('#template').jqote(data); $('#mytable > tbody:last').append(row); }); – PhoebeB Mar 29 '11 at 21:31