我使用 knppaginatorbundle 来创建分页。我创建了一个jquery代码来选择带有ajax的数据。
当我点击页码时,一切都没问题,内容加载了正确的数据。 但我有一个问题,在ajax查询之后,分页模板没有改变:
我该怎么做?
public function listAction($page, Request $request)
{
$em = $this->getDoctrine()->getManager();
$paginator = $this->get('knp_paginator');
$qb = $em->getRepository('AppBundle:Travel')->getListTravels();
$pagination = $paginator->paginate(
$qb, $request->query->get('page', $page), 3
);
//ajax request
if ($request->isXmlHttpRequest()) {
$view = $this->renderView('@App/Frontend/Travel/list.html.twig', array(
'pagination' => $pagination
));
$response = new JsonResponse(array('ok' => $view));
return $response;
}
return $this->render('AppBundle:Frontend/Travel:travel-list-view.html.twig', array(
'pagination' => $pagination,
));
}
我已将attr数据目标添加到分页模板中,如下所示:
<a data-target="{{ page }}" href="{{ path(route, query|merge({(pageParameterName): page})) }}">{{ page }}</a>
查看
//.....
<div id="mydiv">
// list.html.twig contains the loop
{% include "AppBundle:Frontend/Travel:list.html.twig" %}
</div>
<br>
{{ knp_pagination_render(pagination) }}
//....
<script>
$(document).ready(function () {
$("ul#pagination a").click(function (e) {
e.preventDefault();
var dataTarget = $(this).attr("data-target"); // each <a> has attr named data-target contains num of page
var hash;
hash = 'page=' + dataTarget;
window.location.hash = hash;
if (window.location.hash != "") {
$.ajax({
type: 'get',
dataType: 'json',
url: Routing.generate('frontend_travels_list', {'page': dataTarget}),
success: function (msg) {
if (msg["ok"] === undefined) {
alert('error');
} else {
$("#mydiv").html(msg["ok"]);
}
}
});
}
});
});
</script>
路线
frontend_travels_list:
path: /travels/{page}
defaults: { _controller: AppBundle:TravelFrontend:list, page: 1 }
options:
expose: true
答案 0 :(得分:1)
如果其他人需要解决方案,则有2种方法。
您应该在控制器中构建新的分页字符串,并将其作为参数发送到JsonResponse
中。然后成功通过jQuery替换DOM中的分页元素。
对于SF 4.3,您可以使用我的方法
Processor
,必须在services.yaml
Knp\Bundle\PaginatorBundle\Helper\Processor: '@knp_paginator.helper.processor'
基于注入的PaginatorInterface
,您应该构建$pagination
对象(PaginationInterface
)
使用Processor
为Twig构建 context 数组。
$paginationContext = $processor->render($pagination);
render方法期望使用SlidingPagination
对象,但是得到$pagination
的{{1}}-但是似乎还可以
PaginationInterface
工作控制器示例
$twig = $this->get('twig');
$paginationString = $twig->render($pagination->getTemplate(), $paginationContext);
然后在jQuery中
if ($request->isXmlHttpRequest()) {
$view = $this->render('@App/Frontend/Travel/list.html.twig', array(
'pagination' => $pagination
))->getContent();
$paginationContext = $processor->render($pagination);
$twig = $this->get('twig');
$paginationHtml = $twig->render($pagination->getTemplate(), $paginationContext);
$response = new JsonResponse(['view' => $view, 'paginationHtml' => $paginationHtml]);
return $response;
}