【问题标题】:Handlebars external markup with PHP ajax使用 PHP ajax 的车把外部标记
【发布时间】:2015-05-08 13:22:20
【问题描述】:

我想在使用jQuery ajax 与使用PHP 的服务器通信时将所有模板标记文件保存在一个外部html 文件中。 PHP 将只返回 json 对象中的变量数据。

问:如何组织它,以便使用我的 html 模板下面的代码在外部文件中?

jquery:

   $.ajax({ type: "POST",
            async: false,
            url: "ajaxHandler.php",// normally the template, but i need php for dB connect
            dataType: "json",
            success: function(data){
                var aaa = data.aaa,
                        bbb = data.bbb,
                        ccc = data.ccc;
                console.log(aaa+' '+bbb+' '+ccc);       
            }
        });

php:

$aaa = 1;
$bbb = 'bbb';
$ccc = "$aaa $bbb";
echo json_encode(array( "aaa"=>$aaa, "bbb"=>$bbb, "ccc"=>$ccc ));

我的 index.html 包含:

  <table class="entries">
            <script id="template" type="text/x-handlebars-template">
                            <tr>
                                    <td>{{aaa}}</td>
                                    <td>{{bbb}}</td>
                                    <td>{{ccc}}</td>
                            </tr>
            </script>
    </table>

但我想将其保存在外部文件中

【问题讨论】:

    标签: jquery handlebars.js


    【解决方案1】:

    您需要precompile your templatesload and compile the .hbs files with Ajax when requested。之后,您可以从 Handlebars.templates 获取模板,用您的数据填充它并将其附加到您的条目中

    yourtemplate.hbs

    <tr>
      <td>{{aaa}}</td>
      <td>{{bbb}}</td>
      <td>{{ccc}}</td>
    </tr>
    

    JavaScript

       $.ajax({ type: "POST",
                async: true,
                url: "ajaxHandler.php",
                dataType: "json",
                success: function(data){
                    var template = Handlebars.template["yourtemplate.hbs"],
                        html = template(data);
                    $(".entries").append(html);
    
                }
       });
    

    【讨论】:

      猜你喜欢
      • 2018-09-09
      • 1970-01-01
      • 2012-04-23
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      相关资源
      最近更新 更多