小胡子,迭代JSON对象

时间:2012-03-12 17:37:58

标签: javascript jquery mustache

我有一个JSON对象数组,我正在尝试找出如何在Mustache.js中显示它们。数组的长度和内容可以变化。

示例:

[ Object { id="1219", 0="1219", title="Lovely Book ", url= "myurl} , Object { id ="1220" , 0="1220 , title "Lovely Book2" , url="myurl2"}]

我试过了:

        $.getJSON('http://myjsonurl?type=json', function(data) {
        var template = $('#personTpl').html();
        var html = Mustache.to_html(template, data);
        $('#test').html(html);

和模板:

 <script id="personTpl" type="text/template">
TITLE: {{#data}} {{title}} IMAGE: {{image}}
<p>LINK: <a href="{{blogURL}}">{{type}}</a></p>  {{/data}} 
</script>

但是没有显示任何内容。

我已尝试将JSON放入数组中,然后使用products[1]直接访问它:

$.getJSON("http://myjsonurl?type=json", function(json) 
{
    var products = [];

    $.each(json, function(i, product)
    {           
            var product =
            {           
                Title:product.title,
                Type:product.type,
                Image:product.image             
            };

            products.push(product);
        ;       
    });     

    var template = "<h1>Title: {{ Title }}</h1> Type: {{ Type }} Image : {{ Image }}";


    var html = Mustache.to_html(template, products[1]);
    $('#json').html(html);                      

}); 

将显示一条记录正常,但我如何迭代它们并显示所有记录?

3 个答案:

答案 0 :(得分:9)

您需要一个看起来像这样的JSON对象:

var json = { id:"1220" , 0:"1220", title:"Lovely Book2", url:"myurl2" };
var template = $('#personTpl').html();
var html = Mustache.to_html(template, json);
$('#test').html(html);

所以这样的事情应该有效:

$.getJSON('http://myjsonurl?type=json', function(data) {
var template = $('#personTpl').html();
$.each(data, function(key,val) {

        var html = Mustache.to_html(template, val);
        $('#test').append(html);
});

});

答案 1 :(得分:2)

为了让你的模板按照你的方式工作,你的json需要看起来像这样

{
  "data": [
    { "id":"1219", "0":"1219", "title":"Lovely Book ", "url": "myurl"},
    { "id":"1219", "0":"1219", "title":"Lovely Book ", "url": "myurl"},
    { "id":"1219", "0":"1219", "title":"Lovely Book ", "url": "myurl"}
  ]
}

答案 2 :(得分:2)

这应该消除了做每个陈述的需要

var json = { id:"1220", 0:"1220", title:"Lovely Book2", url:"myurl2" };
var stuff = {stuff: json}; 
var template = $('#personTpl').html();
var html = Mustache.to_html(template, stuff);
$('#test').html(html);

在你的模板中,执行此操作以循环浏览内容

<script id="personTpl" type="text/template">
{{#stuff}}
   TITLE:  {{title}} IMAGE: {{image}}
   <p>LINK: <a href="{{blogURL}}">{{type}}</a></p>  
{{/stuff}} 
</script>
相关问题