How can I send JSON response in symfony2 controller

后端 未结 5 1746
栀梦
栀梦 2020-12-04 11:02

I am using jQuery to edit my form which is built in Symfony.

I am showing the form in jQuery dialog and then submitting it.

5条回答
  •  既然无缘
    2020-12-04 11:27

    Symfony 2.1

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

    Symfony 2.2 and higher

    You have special JsonResponse class, which serialises array to JSON:

    return new JsonResponse(array('name' => $name));
    

    But if your problem is How to serialize entity then you should have a look at JMSSerializerBundle

    Assuming that you have it installed, you'll have simply to do

    $serializedEntity = $this->container->get('serializer')->serialize($entity, 'json');
    
    return new Response($serializedEntity);
    

    You should also check for similar problems on StackOverflow:

    • How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?
    • Symfony 2 Doctrine export to JSON

提交回复
热议问题