这真的很奇怪。这是我第一次使用胡子库,当我将其解析为原始对象文字时,此数据在本地工作正常:
{
"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文件并尝试像这样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>
我收到错误说:
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
答案 0 :(得分:2)
您忘记在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>