Bob*_*ing 6 javascript jquery mustache
我有一个JSON对象数组,我正在尝试找出如何在Mustache.js中显示它们.数组的长度和内容可以变化.
例:
[ Object { id="1219", 0="1219", title="Lovely Book ", url= "myurl} , Object { id ="1220" , 0="1220 , title "Lovely Book2" , url="myurl2"}]
Run Code Online (Sandbox Code Playgroud)
我试过了:
$.getJSON('http://myjsonurl?type=json', function(data) {
var template = $('#personTpl').html();
var html = Mustache.to_html(template, data);
$('#test').html(html);
Run Code Online (Sandbox Code Playgroud)
和模板:
<script id="personTpl" type="text/template">
TITLE: {{#data}} {{title}} IMAGE: {{image}}
<p>LINK: <a href="{{blogURL}}">{{type}}</a></p> {{/data}}
</script>
Run Code Online (Sandbox Code Playgroud)
但这并没有显示任何东西.
我已经尝试将JSON放入一个数组中,然后使用以下内容直接访问它 products[1]:
$.getJSON("http://myjsonurl?type=json", function(json)
{
var products = [];
$.each(json, function(i, product)
{
var product =
{
Title:product.title,
Type:product.type,
Image:product.image
};
products.push(product);
;
});
var template = "<h1>Title: {{ Title }}</h1> Type: {{ Type }} Image : {{ Image }}";
var html = Mustache.to_html(template, products[1]);
$('#json').html(html);
});
Run Code Online (Sandbox Code Playgroud)
这将显示一个记录正常,但我如何迭代它们并显示所有?
您需要一个看起来像这样的JSON对象:
var json = { id:"1220" , 0:"1220", title:"Lovely Book2", url:"myurl2" };
var template = $('#personTpl').html();
var html = Mustache.to_html(template, json);
$('#test').html(html);
Run Code Online (Sandbox Code Playgroud)
所以像这样的东西应该工作:
$.getJSON('http://myjsonurl?type=json', function(data) {
var template = $('#personTpl').html();
$.each(data, function(key,val) {
var html = Mustache.to_html(template, val);
$('#test').append(html);
});
});
Run Code Online (Sandbox Code Playgroud)