2012-01-14 69 views
2

这真的很奇怪。它的我第一次用胡子库,这个数据正常工作本地,当我分析它作为原始对象字面:为什么我的json不被胡子解析?

{ 
    "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?" 
     } 
    ] 
} 

这里的胡子模板使用:

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

但当下我把它塞进一个JSON文件,并尝试阿贾克斯这样的:

<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> 

我得到一个错误说:

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?" 
     } 
    ] 
} 

我在做什么错?

直播代码在这里:http://bit.ly/A17pBP

回答

2

你忘了 “数据类型: 'JSON'” 添加到您的AJAX调用!我添加并测试它,它工作正常:

<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> 
+0

是的。我刚刚发现,困难的方式:) – 2012-01-14 17:36:37

相关问题