【问题标题】:Symfony2 The Response content must be a string or object implementing __toString(), "boolean" givenSymfony2 的响应内容必须是实现 __toString() 的字符串或对象,“boolean”给定
【发布时间】:2016-05-11 05:56:12
【问题描述】:

我正在尝试动态渲染模态窗口,问题是当返回我的响应 Json 时,我得到下一个错误:

The Response content must be a string or object implementing __toString(), "boolean" given. 

这是我的控制器:

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;

//Some Code...

public function detallesAction($id)
{
    $em = $this->getDoctrine()->getManager();
    $articulo = $em->getRepository("FicherosBundle:Articulo")->find($id);

    $html = $this->render('FicherosBundle:Articulos:detalles.html.twig', array(
            "articulo"     => $articulo
    ))->getContent();

     $response = new Response(json_encode(array(
            "detalles" =>  $html
     )));
     $response->headers->set('Content-Type', 'application/json');

     return $response;
}

这是我的模板 detalles.html.twig:

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
    <h4 class="modal-title">Detalles</h4>
    <small class="font-bold">En esta ventana se ve reflejada toda la información del articulo.</small>
</div>
<div class="modal-body">
    Hello world
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-white" data-dismiss="modal">Cerrar</button>
</div>

这是我从 index.html.twig 对 AJAX 的调用:

$('.detalles').click(function () {
    var id = $(this).data("id");
    var url = Routing.generate('articulos_detalles', { id: id });
    $.ajax({
        url: url,
        cache: false,
        success: function(response) {
            $(".modal-content").html(response.detalles);
            $("#myModal2").modal("show");
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {

        }
    })
});

问题出在哪里? :/

【问题讨论】:

  • 您在$html 中得到了什么?尝试转储。好像你在 Response. 中得到布尔值
  • json_encode 在失败时返回 false。您还可以使用 JsonResponse 压缩所有响应标头内容。
  • 是的,我在 detalles.html.twig 中出了点问题……:/
  • 只是一个旁注,最好使用return new JsonResponse($array,$code)。更干净,更容易调试。

标签: php json ajax symfony twig


【解决方案1】:

您的 html 似乎无法在 json 中正确编码。

另外你应该直接使用renderView方法和JsonResponse来渲染它,而不需要手动指定headers/encoding json。
这将防止您出现像现在使用自定义响应那样的错误。

应该是:

$html = $this->renderView('FicherosBundle:Articulos:detalles.html.twig', array(
    "articulo"     => $articulo
))->getContent();

return new JsonResponse($html);

希望这会有所帮助。

【讨论】:

  • 是的,这适用于renderView和JsonResponse,但我需要传递一个数组。通常我需要将多个参数传递给json数组
  • 给我一个你想要回报的例子,我会尽力回答你
猜你喜欢
  • 1970-01-01
  • 2014-11-19
  • 2015-10-24
  • 2012-08-20
  • 2017-08-17
  • 2019-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多