Symfony JsonResponse返回呈现模板
在使用ajax创建新元素之后,我的conroller会给出一个JsonResponse。现在我想更新元素列表。因此,我希望在JsonResponse中将新表作为变量 如何在控制器操作中呈现模板Symfony JsonResponse返回呈现模板,symfony,templates,jsonresponse,Symfony,Templates,Jsonresponse,在使用ajax创建新元素之后,我的conroller会给出一个JsonResponse。现在我想更新元素列表。因此,我希望在JsonResponse中将新表作为变量 如何在控制器操作中呈现模板 $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('MyBundle:Entity')->find($id); $em->persist
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('MyBundle:Entity')->find($id);
$em->persist($entity);
$em->flush();
$template = $this->render('MyBundle:Entity:show.html.twig');
return new JsonResponse(array('message' => 'Success!'), 200);
当我添加“template”行时,我在jsonresponse上得到一个错误。实体已正确添加到数据库中
我的模板。show.html.twig
<table class="table table-responsive table-hover">
<thead>
<tr>
<th>Titel</th>
<th>Link</th>
</tr>
</thead>
<tbody>
{% for entity in entities %}
<tr>
<td>{{ entity.titel }}</td>
<td>{{ entity.link }}</td>
</tr>
{% endfor %}
</tbody>
</table>
不要使用json响应,它用于向视图发送数组或对象之类的数据。您希望使用
$this->render
,然后作为ajax成功函数,您可以使用如下内容
function(msg){
$e = $('your_element'); // this is where you want to display the received data
$e.html(msg);
}
有关ajax、Symfony2和Json的更多信息,请参阅。
$this->render(…
可以。你有什么问题吗?在插入这一行后,我得到了一个错误的JsonResponse。我的路由正确吗?Bundlename:Entityname:Templatename?我的模板放在Resources/views/Entityname中。请发布所有相关的代码/错误。目前这只是猜测。$this->render
将为你提供一个字符串(可能是html),这完全取决于你如何进一步使用这个字符串。错误仍然没有出现。我也这样做过很多次,从来没有遇到过任何问题。不过,我有一种感觉,在渲染时,你可能必须将必要的变量传递给MyBundle:ENtity:show.html.twig
。例如$this->render('MyBundle:Entity:show.html.twig',array('Entity'=>$Entity))
?同样,如果出现错误和相关代码会有所帮助,或者我们可以一直猜测。请查看我上面的编辑,并尝试找出调用模板时的错误所在,好吗?
function(msg){
$e = $('your_element'); // this is where you want to display the received data
$e.html(msg);
}