【问题标题】:Get data from Json and rendering in html(with bootstrap) ajax call and mustache template从 Json 获取数据并在 html 中呈现(使用引导程序)ajax 调用和 mustache 模板
【发布时间】:2018-05-08 08:31:39
【问题描述】:

我的网站是用引导程序构建的。我想用存储在 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);
});

谁能帮帮我?

【问题讨论】:

  • 欢迎来到 SO。感谢您正确包含您的代码,但不幸的是您没有提出问题。什么不起作用?
  • 将我的数据渲染成 html ...我必须对我的数组做一个 $each

标签: jquery html ajax templates mustache


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 1970-01-01
    • 2010-10-27
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    相关资源
    最近更新 更多