Json 内容使用 Jquery 和小胡子 - wamp

Json content using Jquery and Mustache - wamp

我的 wamp 服务器中有一个带有 MUSTACHE 模板的 HTML 文件 + JSON 文件。 我想用 JSON 的内容填充我的 HTML。 为什么它现在可以工作了?

.HTML

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Mustache Sample</title>
    </head>


    <body>
        <div id="speakerbox">
            <div id="carousel"></div>
        </div>

    <!--template-->
    <script id="speakerstpl" type="text/template">
        {{#speakers}}
            <div class="speakers">
                <h3>{{shortname}}</h3>
            </div>
        {{/speakers}}
    </script>

    <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/mustache.js/0.8.1/mustache.min.js"></script>


    <script type="text/javascript">
        $(function(){
            $.getJSON('data.json', function (data){
                    var template = $('#speakerstpl').html();
                    var html = Mustache.to_html(template, data);
                    $('#carousel').html(html);
            }); //get json
        });//function
    </script>    

    </body>
    </html>

.JSON

[
  {
    "speakers": [
      {
        "name": "ana", 
        "shortname": "ann",
        "bio": "biogg"
      }, 
      {
        "name": "bolacha", 
        "shortname": "bol",
        "bio": "biogg de bolacha"
      }
     ]
  }
]

Json有问题吗?

我在 HTML 中遗漏了什么?

感谢您的帮助!

问题是您将 speakers 包含在数组中,这意味着您需要使用 data[0] 作为 to_html (fiddle) 的参数:

   $(function(){
        $.getJSON('data.json', function (data){
                var template = $('#speakerstpl').html();
                var html = Mustache.to_html(template, data[0]);
                $('#carousel').html(html);
        }); //get json
    });//function

或者您可以删除封闭数组,在这种情况下您的 json 看起来像 (fiddle):

{
    "speakers": [
      {
        "name": "ana", 
        "shortname": "ann",
        "bio": "biogg"
      }, 
      {
        "name": "bolacha", 
        "shortname": "bol",
        "bio": "biogg de bolacha"
      }
     ]
  }