首页 > 解决方案 > 从 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);
});

谁能帮我?

标签: jqueryhtmlajaxtemplatesmustache

解决方案


你的数据以数组的形式返回,所以改变这个

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);

推荐阅读