我听说过有关 Mustache 的精彩内容,并决定尝试一下。
我正在尝试弄清楚如何将 Mustache 模板与 jQuery 一起使用。我已经搜索了几天了。
mustache 可以在这里找到:https://github.com/janl/mustache.js/
这是我的尝试:
$.getJSON('get_fullname.asp', {name: 'johnny'}, function(data, status, xhr) {
var template = '<h1>{{NAME}}</h1><p>test</p>';
strHTML = Mustache.to_html(template, data);
$('#container').html( strHTML );
});
我的 JSON 数据返回 [{"NAME":"John","MIDDLE":"A","LAST":"Smith"}]
我得到的是<p>test</p>
.
我也试过使用这个模板,但仍然得到 <p>test</p>
.
var template = '{{#NAME}}<h1>.</h1>{{/NAME}}<p>test</p>';
我错过了什么?
最佳答案
乍一看,您的 JSON 对象似乎嵌套在一个数组中。删除它周围的 [] ,然后看看它是否有效。您可以在服务器级别(我推荐)或在 javascript 中调用:
strHTML = Mustache.to_html(template, data[0]);
代替:
strHTML = Mustache.to_html(template, data);
关于javascript - 如果 JSON 对象位于嵌套数组中,如何使用 Mustache.js?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5516852/