Paginationjs, handlebars, ajax call and JSON



我正在尝试将分页JS与AJAX加载的内容一起使用。 这是代码

<div class="container container-fluid">
<div id="review-container"></div>
<div id="review-pagination"></div>
</div>
<script type="text/template" id="template-review">
<div class="review__list">
{{#each data}}
{{state}}
{{rate}}
{{/each}}
</div>
</script>
<script>
jQuery('#review-pagination').pagination({
dataSource: function(done) {
jQuery.ajax({
type: 'GET',
url: '/reviews.json',
beforeSend: function() {
jQuery('#review-container').html('<?php echo $this->__("Récupération des avis..."); ?>');
},
success: function(response) {
done(response);
}
});
},
locator: 'data',
pageSize: 5,
showPrevious: false,
showNext: false,
callback: function(data, pagination) {
console.log("===> "+typeof(data));
console.log(data);
//var data = JSON.stringify({ data: data });
var html = Handlebars.compile(jQuery('#template-review').html(), {
data: data
});
jQuery('#review-container').html(html);
}
})
</script>

无论数据源类型(URL、函数(如何,车把似乎都无法在 {{#each}} 中循环

这是两个控制台的结果.log在回调中

:1790 ===> object
:1791 (5) [{…}, {…}, {…}, {…}, {…}]
0: {state: "4", rate: "4", canal: "online", id_review: "eb53a2a3-09aa-42e4-b475-6233383ee634", order_ref: "100246459", …}
1: {state: "4", rate: "5", canal: "online", id_review: "cb581889-2439-4e43-b36b-dbfdc5ae1139", order_ref: "100244923", …}
2: {state: "4", rate: "4", canal: "online", id_review: "77506f2f-9b77-41a3-9e4c-37b477c943ce", order_ref: "100250211", …}
3: {state: "4", rate: "5", canal: "online", id_review: "de85eba0-4e84-4c47-915c-5fdf0157eb5b", order_ref: "100249780", …}
4: {state: "4", rate: "5", canal: "online", id_review: "b77f6a0f-9dd8-47cd-ad73-4bff3150e832", order_ref: "100251412", …}
length: 5
__proto__: Array(0)

分页生成良好,但缺少所有内容(来自 json(。好像它是空的。

请有人帮忙吗?

您的问题是您尝试使用调用Handlebars.compile的结果,就好像它是 HTML 字符串一样,但Handlebars.compile返回函数,而不是字符串。

使用车把实际上有两个部分:

  1. 将模板编译为模板函数。
  2. 使用上下文数据调用模板函数。

您尝试通过将上下文数据传递给Handlebars.compile调用来将这两个步骤合并为一个步骤,但这不起作用。您需要在执行模板函数之前进行编译。

var template = Handlebars.compile(jQuery('#template-review').html());
var html = template({
data: data
});
jQuery('#review-container').html(html);

此外,明智的做法是将编译移出callback函数,因为您不需要多次编译模板(编译的模板函数不会更改,只会更改时调用它的上下文值(。

我创建了一个小提琴供您参考。

最新更新