为什么我的json不会被Mustache解析?

时间:2022-10-24 22:44:05

This is really weird. Its my first time with using the mustache library and this data works fine locally when I parse it as a raw object literal:

这真的很奇怪。这是我第一次使用mustache库,当我将它解析为一个原始对象文字时,这个数据在本地运行良好:

{
   "datacenters":[
      {
         "title":"Flinders St Station",
         "description":"This is a pretty major train station."
      },
      {
         "title":"Southern Cross Station",
         "description":"Did you know it used to be called Spencer St Station?"
      }
   ]
}

Here's the mustache template I use:

这是我用的胡子模板:

<script id="dinfoTpl" type="text/template"> 
    {{#datacenters}}
    <h1>{{title}}</h1>
    <p>{{description}}</p>
    {{/datacenters}}    
</script>

But the moment I tuck it in a json file and try to ajax it like this:

但是,当我将它放入json文件并尝试ajax时,就像这样:

<script type="text/javascript">

        var data, template, html;

        $.ajax({
            url: "datacenter.json",
            success: function(data) {
                var template = $('#dinfoTpl').html();
                var html = Mustache.to_html(template, data);
                $('#output').html(html);            
            }       
        });

</script>

I get an error saying:

我得到一个错误的答案:

Uncaught TypeError: <template>:2

 >>         {{#datacenters}}
            <h1>{{title}}</h1>
            <p>{{description}}</p>
            {{/datacenters}}    

Cannot use 'in' operator to search for 'datacenters' in {
   "datacenters":[
      {
         "title":"Flinders St Station",
         "description":"This is a pretty major train station."
      },
      {
         "title":"Southern Cross Station",
         "description":"Did you know it used to be called Spencer St Station?"
      }
   ]
}

What am I doing wrong?

我做错了什么?

Live code here: http://bit.ly/A17pBP

住代码:http://bit.ly/A17pBP

1 个解决方案

#1


2  

You forgot to add "dataType: 'json'" to your Ajax call! I added and test it and it works fine:

您忘记在Ajax调用中添加“dataType: 'json' !”我添加并测试了它,效果很好:

<script type="text/javascript">

        var data, template, html;

        $.ajax({
            url: "datacenter.json",
            dataType: 'json',
            success: function(data) {
                var template = $('#dinfoTpl').html();
                var html = Mustache.to_html(template, data);
                $('#output').html(html);            
            }       
        });

</script>

#1


2  

You forgot to add "dataType: 'json'" to your Ajax call! I added and test it and it works fine:

您忘记在Ajax调用中添加“dataType: 'json' !”我添加并测试了它,效果很好:

<script type="text/javascript">

        var data, template, html;

        $.ajax({
            url: "datacenter.json",
            dataType: 'json',
            success: function(data) {
                var template = $('#dinfoTpl').html();
                var html = Mustache.to_html(template, data);
                $('#output').html(html);            
            }       
        });

</script>