2010-11-16 24 views
0

我知道我搞亂了某處的語法,但我無法弄清楚在哪裏。下面的代碼。 (我離開了身體標記,因爲它沒有正確顯示在預覽)如何從JSON和JQuery模板構建HTML

<head runat="server"> 
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script> 
    <script src="Scripts/jquery.tmpl.js" type="text/javascript"></script> 
    <script src="Scripts/jquery.tmplPlus.js" type="text/javascript"></script> 
    <script id="ProductsTemplate" type="text/x-jquery-tmpl"> 
     <table class="productsHere"> 
      <thead> 
       <tr> 
        <td>Title</td> 
        <td>Size</td> 
        <td>Price</td> 
       </tr> 
      </thead> 
      <tbody> 
       {{each data}} 
        {{tmpl($value) '#ProductsRowTemplate'}} 
       {{/each}} 
      </tbody>    
     </table> 
    </script> 
    <script id="ProductsRowTemplate" type="text/html"> 
     <tr> 
      <td class="title">${title}</td> 
      <td class="size">${size}</td> 
      <td class="price">${price}</td> 
     </tr> 
    </script> 
    <title>Using JQuery</title> 
</head> 

<script type="text/javascript"> 
    $(document).ready(function() { 
     $.ajax({ 
      type: "POST", 
      url: "JSON-WebService.asmx/getProducts", 
      data: "{}", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function (data) { 
       $('#ProductsTemplate').tmpl(data).appendTo('#ProductsTable'); 
       alert("It works"); 
      }, 
      failure: function (data) { 
       alert("It didn't work"); 
      } 
     }); 
    }); 
</script> 

<div id="ProductsTable"></div> 
<div id="OthersTable"></div> 
<div></div> 

</form> 
+0

什麼是您會收到錯誤消息? – Jake 2010-11-16 17:41:44

+0

根據我的警報,我可以得到:「它有效」,但表格不是渲染。我看到的只是標題。我也沒有收到錯誤消息。 – dotnetN00b 2010-11-16 18:20:13

回答

1

假設你正在使用.NET 3.5+和返回的getProducts像一個列表或數組的集合,你需要以計入the .d that .NET wraps your data with。由於您的{{each}}循環需要對數組的引用,無論如何,你可以通過改變你的模板,像這樣利用.D的:

<script id="ProductsTemplate" type="text/x-jquery-tmpl"> 
    <table class="productsHere"> 
    <thead> 
     <tr> 
     <td>Title</td> 
     <td>Size</td> 
     <td>Price</td> 
     </tr> 
    </thead> 
    <tbody> 
     {{each d}} 
     {{tmpl($value) '#ProductsRowTemplate'}} 
     {{/each}} 
    </tbody> 
    </table> 
</script> 
+0

啊。好的,我得到了正確數量的行,但是我得到了9次頭(實際數據庫表中有9條記錄,所以這部分是正確的)。是的,我正在使用.NET 4.0,並且Web服務正在返回一個數組。 – dotnetN00b 2010-11-16 18:27:02

+0

我改變了主意,並更新了我的答案。既然你的'{{each}}'無論如何都需要引用循環,只需傳入'data'而不是'data.d',然後使用'.d'來指定要循環的內容。這將解決您看到標題重複9次的問題,而不是執行9次的{{tmpl}}。 – 2010-11-16 23:24:44

+0

你是對的錢!謝謝;真的很感激它! – dotnetN00b 2010-11-17 03:44:11