Reputation: 12281
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:
{
"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:
<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
Upvotes: 2
Views: 1185
Reputation: 5905
You forgot to add "dataType: 'json'" to your Ajax call! I added and test it and it works fine:
<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>
Upvotes: 2