使用 PHP ajax 的车把外部标记
Handlebars external markup with PHP ajax
我想将所有模板标记文件保存在外部 html 文件中,同时使用 jQuery
ajax 使用 PHP
与服务器通信。 PHP 将 return 仅 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>
但我想将其保存在外部文件中
您需要 precompile your templates or load 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);
}
});
我想将所有模板标记文件保存在外部 html 文件中,同时使用 jQuery
ajax 使用 PHP
与服务器通信。 PHP 将 return 仅 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>
但我想将其保存在外部文件中
您需要 precompile your templates or load 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);
}
});