Symfony:发送 JsonResponse

问题描述 投票:0回答:1

我是 symfony 作为 Web 编程的新手,并且在使用 JSON 响应方面遇到了困难。

如您所见,控制器显示实体内容并创建一个表单以在其中添加数据。表单工作正常,AJAX 发送的数组已添加到实体中,但想法是将此数据作为 JSON 响应发送回,以更新实体内容,而不刷新整个页面。

问题是,当发送表单时,JSON 响应会替换页面并显示类似以下内容:

{
"success": true,
"new_object": {
"id": 27,
"name": "thename",
"description": "thedescription",
"date": "2024-03-23T10:22:00+00:00",
}
}

我认为在定义函数时应该将 Response 替换为 JsonResponse,但视图的渲染会发送错误,要求提供 JSON 响应。

我还努力创建一个新函数来发送 JSON 响应,但由于 $form 正在处理请求,我看不到如何将表单添加到页面中,这在另一个函数中是单独的。

那么我应该如何发送这个 JSON 响应?非常欢迎任何帮助👍

<?php

namespace App\Controller;

use App\Entity\MyEntity;
use App\Form\OffresFormType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;

class MyEntityController extends AbstractController
{
    /**
     * @Route("/admin", name="administration", methods={"GET", "POST"})
     */
    public function admin(Request $request, EntityManagerInterface $entityManager): Response
    {

        $newobject = new MyEntity();
        $form = $this->createForm(MyEntityFormType::class, $newobject);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager->persist($newobject);
            $entityManager->flush();

            return $this->json(['success' => true, 'newobject' => $newobject]);
        }

        return $this->render('admin/entity.html.twig', [
            'entity_content' => $entityManager->getRepository(MyEntity::class)->findAll(),
            'form' => $form->createView(),
        ]);
    }
}
php symfony jsonresponse
1个回答
0
投票

尝试使用“JsonResponse”来替换“return $this->json”,如下所示:

    if ($form->isSubmitted() && $form->isValid()) {
            $entityManager->persist($newobject);
            $entityManager->flush();

            return new JsonResponse([
              'success' => true, 
              'newobject' => $newobject
            ]);
        }
© www.soinside.com 2019 - 2024. All rights reserved.