jquery - 从 Json 获取数据并在 html 中呈现(使用引导程序)ajax 调用和 mustache 模板
问题描述
我的网站是用引导程序构建的。我想用存储在 JSON 文件中的数据创建一个 div,并用小胡子进行渲染。我在小胡子模板的 HTML 中有脚本:
<script id="plutos" type="text/template">
<div class="col-sm-12 col-md-6 col-xl-4">
<h3 class="text-center" >{{title}}</h3>
<img src="{{picture}}" style="width:100%">
<p class="text-justify" class="text-center">{{plot}}</p>
<button type="button" class="btn btn-primary btn-xs red">
<i class="fa fa-fw fa-thumbs-up"></i>
</button>
</div>
</script>
我的articles.json 用数组存储数据
[{
"title": "Casa",
"picture": "img/portfolio/cabin.png",
"plot": "Per casa si intende una qualunque struttura utilizzata dagli esseri umani per ripararsi dagli agenti atmosferici. Essa generalmente ospita uno o più nuclei familiari e talvolta anche animali.",
"like": false
},
// ...
我有这个用于 AJAX 调用的 JS:
$.ajax({
method: "GET",
url: "articles.json",
}).done(function( msg ) {
var template = $('#plutos').html();
var html = Mustache.to_html(template, msg);
$('#portfolio').html(html);
});
谁能帮我?
解决方案
你的数据以数组的形式返回,所以改变这个
var html = Mustache.to_html(template, msg);
至
var html = Mustache.to_html(template, msg[0]); // [0] -> get the first object.
如果可行,那么您可以遍历数组以获取每个对象。
Fwiw,我习惯了使用的不同版本render
:
var html = Mustache.render(template, msg);
推荐阅读
- mysql-error-1064 - 如何在 id 明智的情况下列值显示 null 或 0
- sql - TYPO3逻辑或数据库查询中的优先级
- c# - C#中的自定义模式匹配
- javascript - 开玩笑匹配器匹配三个值中的任何一个
- testing - Ember JS 测试 - 工厂人
- mongodb - 如何将isodate的mongodb日期字段转换为本地日期
- flutter - 不包含脚手架错误。我知道我的方法没有脚手架方法,但它是具有脚手架的方法的子方法
- java - 如何简化这段代码?
- r - 我可以将一个 PCA 的变量坐标覆盖在来自第二个 PCA 的个人坐标上并仍然解释结果吗?
- angular - 部署到 AWS 服务器后,Angular 4/5 中仅加载默认 url 组件