2013-01-09 17 views
0

我有一個Html列表,我從REST調用接收數據作爲JSON字典,我遍歷並獲取它們的值。但我找不到如何用循環中的項目生成Html。如何填充循環中的HTML列表

<div class="container"> 
<ul role="list"> 
    <li class="infoBasic" role="listitem"> 
     <div class="date">20-12-2012</div> 
     <div class="ammount">-&euro;4,25</div> 
    </li> 
    <li class="infoDetails" role="listitem"> 
     <div class="place">data</div> 
     <div class="category">data</div> 
     <div class="description_title">data</div> 
     <div class="description">data</div> 
    </li> 

    //repeat this for multi items received from REST 

</ul> 

$.ajax 
    ({ 

    success: function (data){      
     var transactions=data['transactions'];  

     $.each(transactions, function(key, value) { 
      $.each(value, function(key, value) { 

       //here how to set/create the appropriate div elements(like above) 
       // with the values I get here in a loop? 

      });       
     }); 

編輯下面的一些解決方案是好的,但我不想從我的對象數組中的所有值,我怎麼能得到的只有這些項目(日期,金額,place..etc)在HTML DIV和忽略詞典

+1

請提供來自服務器的JSON響應的樣本。 –

回答

1

你可以使用..

 var data = ""; 

    $.each(transactions, function(key1, value1) { 
     data +="<li class ='"+ key1 +"' role='listitem'>"; 

      $.each(value1, function(key, value) { 
       data +="<div class ='"+ key +"'>"+value+"</div>"; 
      }); 
    }); 


    $("ul").html(data); // selecting ul element and then embedding html into it.. 
+0

thx,我的問題是我需要從列表中的一些值不遍佈他們我怎麼能做到這一點? – Spring

1
$.each(value, function(key, value) { 

      //here how to set/create the appropriate div elements(like above) 
      // with the values I get here in a loop? 

      $(".infoDetails").append("<div class='" + key + "'>" + value + "</div>"); 
     }); 
+0

tnx我不知道我將收到的項目數量,如何更改上面的當前html? – Spring

-1

其他項目試...帶可變說HTML ...通過JSON數組迭代...在列表中添加項目......而把整個HTML在一個div裏面..

var html='<ul>'; 
$.ajax 
    ({ 

    success: function (data){      
     var transactions=data['transactions'];  

     $.each(transactions, function(key, value) { 
      $.each(value, function(key, value) { 
       html+='<li class="'+key+'">'+value+'</li>'; 
      });       
     }); 
     } 
}); 
html+='</ul>'; 
$('#idofdiv').html(html); 
+0

tnx我不知道我將收到的項目數量,我如何更改上面的當前html? – Spring

+0

如果您有大量數據作爲一個響應進入,您必須有一種方法可以知道您的響應應該適合哪種類型的響應。 – cggaurav

+1

這不會按預期工作。在成功回調到達之前,您會追加一個空列表'

    '。 – Shmiddty