return 新响应 return 空数据

return new Response return empty data

在控制器中,我有 getVilla 方法,其中 return json 响应。 我从 $villa 变量中的数据库中通过 id 获得了一栋别墅,这工作正常。当我 print_r($villa) 我有包含所有数据的别墅对象。 但是当我按下 $villa 作为回应时 json_encode: json_encode(['villa' => $villa]), 别墅是空的...

villa: {}
 /**
     * @Route("/ajax/{id}", name="app_post_front_ajax_villa")
     * @param $id
     * @param EntityManagerInterface $em
     * @return Response
     */
    public function getVilla($id, EntityManagerInterface $em): Response
    {

        $repository = $em->getRepository(Villa::class);
        $villa = $repository->findOneBy(['id' => $id]);

        return new Response(json_encode([
            'villa' => $villa,
        ]));
    }

您正在从响应中返回 json 响应,因此您应该改用 JsonResponse:

use Symfony\Component\HttpFoundation\JsonResponse;

//...

return new JsonResponse([
            'villa' => $villa,
        ]);

但是,您的数组包含对象 $villa,而不是 array。 因此,您应该从 villa 对象创建一个新数组或将其序列化。

简单的方法是从别墅制作一个新阵列:

public function getVilla($id, EntityManagerInterface $em): Response
    {

        $repository = $em->getRepository(Villa::class);
        $villa = $repository->findOneBy(['id' => $id]);

        if($villa){
            $villaArray['id'] = $villa->getId();
            $villaArray['cityNameOrSomething'] = $villa->getCityName();
            //Do the same for other attribute you want to get in your json
        }else{
            $villaArray = [];
        }
        return new Response([
            'villa' => $villaArray,
        ]);
    }

另一种方法是使用 serializer 组件,这样您就不必创建新数组。 只需按照用法上的 Symfony Documentation 找到您要使用的那个即可。