[英]Return a Json Response from a Controller in Symfony
I am trying return a JSON response from a controller in Symfony 3.4 我正在尝试从Symfony 3.4中的控制器返回JSON响应
This is my controller: 这是我的控制器:
/**
* @Route("/message/board/post", name = "message_post")
* @Method("POST")
*/
public function postMeg(Request $request)
{
$entityManager = $this->getDoctrine()->getEntityManager();
$message = new message($request->request->get("txtName"));
$message->setMes($request->request->get("txtMes"));
$entityManager->persist($message);
$entityManager->flush();
return new JsonResponse(['result' => 'ok', 'ret' => array($entityManager)]);
}
But I get {"result":"ok","ret":[{}]} as Response in the browser 但是我在浏览器中得到了{“ result”:“ ok”,“ ret”:[{}]}作为响应
I hope it can show like ['result' => 'ok', 'ret' => txtName, txtMes ] 我希望它可以显示为['result'=>'ok','ret'=> txtName,txtMes]
You should use $message
instead of $entityManager
as mentioned in the comments but passing the entity to new JsonResponse()
will only include public
properties from the message entity and they are usually all private
. 您应该使用
$message
而不是注释中提到的$entityManager
,但是将实体传递给new JsonResponse()
只会包括消息实体的public
属性,并且通常都是private
属性。 There are many ways to do this, but the easiest is just to insert exactly what you want with the entity's getters: 有很多方法可以做到这一点,但是最简单的方法就是在实体的getter中插入所需的内容:
return new JsonResponse([
'result' => 'ok',
'ret' => [
'txtName' => $message->getTxtName(),
'txtMes ' => $message->getTxtMes(),
],
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.