如何使用车把处理来自JSON的数据

时间:2019-01-22 19:43:45

标签: javascript handlebars.js

我有下一个问题,我的html加载时需要获取一些信息。该信息来自api rest,因此我有一个执行该操作的ajax函数和html。 除了将handlebars标签放入脚本中,然后添加附加的div,我没有找到其他方法。

是另一种方式吗?

$(document).ready(

  function obtenerProperties(){
   $.ajax({
     url: "http://127.0.0.1:9000/property?type=URL",
     success: function(data){

      var source = $("#properties-template").html();

      var template = Handlebars.compile(source);

     $(".prueba").append(template(data));

     },
      error: function(data) {
      console.log('error', data);
      }
   })
   }

 );

HTML:

     <body>
    <script id="properties-template" type="text/x-handlebars-template">
        <div class="">
            <table class="table">
                <thead class="thead-dark">
                    <tr>
                        <th scope="col">Nombre</th>
                        <th scope="col">Tipo</th>
                        <th scope="col">Cron</th>
                    </tr>
                </thead>
                <tbody>
                        {{#each properties}}
                    <tr>

                        <th scope="row">1</th>
                        <td>{{clave}}</td>
                        <td>{{valor}}</td>
                        {{/each}}
                    </tr>
                </tbody>
            </table>
        </div>
  </script>
  <div class="prueba">
  </div>
</body>

1 个答案:

答案 0 :(得分:0)

经过编辑的答案,我将$ajax调用放在html主体内的单独脚本选项卡中,并将pruba类移至“ tbody”。

 `<body>
<script>
$(document).ready(
  function obtenerProperties(){
   $.ajax({
 url: "http://127.0.0.1:9000/property?type=URL",
 success: function(data){
  var source = $("#properties-template").html();
  var template = Handlebars.compile(source);
 $(".prueba").append(template(data));
 },
  error: function(data) {
  console.log('error', data);
  }
 })
});
</script>
<script id="properties-template" type="text/x-handlebars-template"/>
    <div class="">
        <table class="table">
            <thead class="thead-dark">
                <tr>
                    <th scope="col">Nombre</th>
                    <th scope="col">Tipo</th>
                    <th scope="col">Cron</th>
                </tr>
            </thead>
            <tbody class="prueba">
                    {{#each properties}}                   
                    {{data}}                      
                    {{/each}}                  
            </tbody>
        </table>
    </div>
</body>`