我有一个控制器动作:
/**
* Get the template for the notifications in the user-navbar
*
* @Route("/notification/get-template", name="get_notifications_template")
* @param Request $request
* @return Response
*/
public function getNotificationsTemplateAction(Request $request)
{
if (!$request->isXmlHttpRequest()) {
return $this->redirect($this->generateUrl('homepage'));
}
return $this->render('Menu/_notifications_block.html.twig');
}
我要进行AJAX调用以获取此模板:
refreshNotifications() {
$.ajax({
url: this.$wrapper.data('refresh-action-path'),
method: 'POST',
}).then(function (data) {
// remove old notifications
this.$wrapper.remove();
// append data to the container
$('#user-notifications-container').append(data);
console.log(data);
}.bind(this))
}
现在的问题是-Symfony容器发送了整个html页面:
模板是:
{% if app.user is not null and is_granted('ROLE_USER') %}
{% if app.user|notifications|length != 0 %}
{% set notifications = app.user|notifications %}
{% set all_notification_count = notifications|length %}
<li class="nav-item mx-2 dropdown js-notification-wrapper data-refresh-action-path="{{ path('get_notifications_template') }}"">
<a href="#" class="icon-wrapper nav-link btn-lg" data-toggle="dropdown">
<span class="icon icon-mail" aria-hidden="true"></span>
<span class="badge badge-notification">{{ all_notification_count }}</span>
</a>
<ul class="dropdown-menu dropdown-menu-right notification-list">
{% if app.user is not null and is_granted('ROLE_USER') and all_notification_count != 0 %}
{% for notification in notifications %}
<div class="notification-text">
<div class="d-flex">
<div class="col-10 px-0">
Kurszugang: {{ notification.courseAction.course }} ({{ notification.courseAction.course.school }})
- {{ notification.courseAction.schoolUser }}
</div>
<div class="col-2">
<button class="btn btn-sm btn-success" id="js-accept-course-action" data-course-action-path="{{ path('course_action_accept_join_request', {'courseAction' : notification.courseAction.id}) }}">
<i class="icon icon-thumbs-up"></i>
</button>
<button class="btn btn-sm btn-secondary" id="js-decline-course-action" data-course-action-path="{{ path('course_action_decline_join_request', {'courseAction' : notification.courseAction.id}) }}">
<i class="icon icon-thumbs-down"></i>
</button>
</div>
</div>
</div>
</li>
{% endfor %}
{% endif %}
</ul>
</li>
{% endif %}
{% endif %}
有人可以告诉我-为什么我不仅可以剪切掉,而且不能整个HTML页面?
我无法将整个页面附加到容器中...
答案 0 :(得分:1)
我对它的理解方式render
返回完整的响应(带有标题),而renderView
仅返回html。
尝试更改此行:
return $this->render('Menu/_notifications_block.html.twig');
对此:
return new JsonResponse([
'html'=> $this->renderView('Menu/_notifications_block.html.twig')
]);
然后在ajax函数中进行更改:
$('#user-notifications-container').append(data);
对此:
$(data.html).appendTo('#user-notifications-container');