-2

在使用 ajax 创建一个新元素后,我从我的控制器中获得了一个 JsonResponse。现在我想更新元素列表。因此,我希望将新表作为 JsonResponse 中的变量。

如何在我的控制器操作中呈现模板?

        $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);

当我添加“模板”行时,我的 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>

我的电话

$template = $this->render('MyBundle:Entity:show.html.twig', array('entities'=> $entities));
4

1 回答 1

0

不要使用 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 的更多信息,请参阅

于 2015-09-09T13:23:41.607 回答