【问题标题】:Symfony JsonResponse return rendered templateSymfony JsonResponse 返回渲染模板
【发布时间】:2015-09-09 12:03:26
【问题描述】:

使用 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));

【问题讨论】:

  • $this-&gt;render(... 将工作。你遇到了什么问题?
  • 在插入此行后,我收到了一个错误的 JsonResponse。我的路由正确吗?捆绑名称:实体名称:模板名称?我的模板放在 Resources/views/Entityname
  • 请发布您遇到的所有相关代码/错误。目前这只是猜测。 $this-&gt;render 会给你一个字符串(可能是html),这完全取决于你如何进一步使用这个字符串。
  • 这个错误还是不见了。
  • 我也做过很多次,从来没有遇到过任何问题。不过,我有一种感觉,您可能必须在渲染时将必要的变量传递给MyBundle:ENtity:show.html.twig。例如$this-&gt;render('MyBundle:Entity:show.html.twig', array('entity' =&gt; $entity))?同样,出现错误和相关代码会有所帮助,或者我们可以一直猜测。

标签: symfony templates jsonresponse


【解决方案1】:

不要使用 json 响应,它用于将数组或对象等数据发送到视图。你想使用$this-&gt;render,然后作为ajax成功函数你可以有这样的东西

function(msg){

    $e = $('your_element'); // this is where you want to display the received data
    $e.html(msg);
}

有关 ajax、Symfony2 和 Json 的更多信息,请参阅 This

【讨论】:

  • 你能看看我上面的编辑并试着找出我在调用模板时做错了什么吗?
猜你喜欢
  • 1970-01-01
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多