2010-02-06 32 views
3

我還是JSON/jQuery的新手。使用jQuery爲複雜對象動態更新html表格使用jQuery進行復雜對象

我需要一些關於如何在客戶端動態填充Html表的快速指導。我的表格有固定的列,但行數會根據檢索的數據動態增長。

說我有服務器上的Web方法(GetActiveUsers),返回,稱爲n-用戶。 我使用這個SQL語句:

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

請給我示例代碼

編輯

我對這個解決方案對這個職位here 謝謝你們

+0

你在使用什麼平臺? PHP? ASP.net mvc? – leora 2010-02-06 13:31:10

+0

你可以發佈一個返回給你的JSON的例子嗎? – 2010-02-06 13:38:39

+0

@oo我正在使用Asp.net表格 @Russ我沒有示例JSON,我實際上熱衷於提供可能的JSON格式 – 2010-02-06 21:34:13

回答

3

這是一個完美的應用jQote jQuery的javascript模板引擎。 你可以從這裏取回:http://aefxx.com/jquery-plugin/jqote

例如,考慮以下幾點:

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

現在,這裏是你會在你的HTML定義模板(您或任何輸出文件):

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

所以,我們幾乎完成。讓我們定義我們的包含表並在json數據 上調用jQote來神奇地填充表。

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

這一切(當然這僅僅是個開始,jQote是方式更強大的比我可以告訴你,在這裏)。

希望你喜歡它,試試看。

順便說一句:使用作爲您的模板的容器是完全合法的標記。瀏覽器在任何情況下都不會顯示它。

+0

花了我一段時間來弄清楚如何從ajax調用中使用json來饋送jqote 。這裏有一個方法:var jsondata = $ .getJSON('/ path/to/call /', function(data){ row = $('#template')。jqote(data); $('#/ mytable> tbody:last')。append(row); }); – PhoebeB 2011-03-29 21:31:14