【发布时间】: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">×</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