如何在symfony2控制器中发送json响应?

时间:2022-06-04 06:38:27

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

我正在使用jQuery来编辑我在Symfony中构建的表单。

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

我在jQuery对话框中显示表单,然后提交。

Data is entering correctly in database.

数据正在数据库中正确地输入。

But I don't know whether I need to send some JSON back to jQuery. Actually I am bit confused with JSON thing.

但我不知道是否需要将JSON发送回jQuery。实际上,我对JSON有点困惑。

Suppose I have added a row in my table with jQuery and when I submit the form then after data is submitted I want to send back those row data so that I can dynamically add the table row to show the data added.

假设我在我的表中添加了一个与jQuery的行,当我提交表单后,在提交数据之后,我想要返回这些行数据,这样我就可以动态地添加表格行来显示添加的数据。

I am confused how can get that data back

我搞不懂怎么把这些数据拿回来。

This is my current code

这是我现在的代码。

$editForm = $this->createForm(new StepsType(), $entity);

$request = $this->getRequest();

$editForm->bindRequest($request);

if ($editForm->isValid()) {
    $em->persist($entity);
    $em->flush();

    return $this->render('::success.html.twig');               
}

This is just the template with success message

这只是成功消息的模板。

5 个解决方案

#1


174  

Symfony 2.1

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

Symfony 2.2和更高版本

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

您有特殊的JsonResponse类,它将数组序列化为JSON:

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

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

但是如果您的问题是如何序列化实体,那么您应该看看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 *:

您还应该检查*上类似的问题:

#2


54  

Symfony 2.1 has a JsonResponse class.

Symfony 2.1有一个JsonResponse类。

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

The passed in array will be JSON encoded the status code will default to 200 and the content type will be set to application/json.

在数组中传递的将是JSON编码的状态码将默认为200,内容类型将被设置为application/ JSON。

There is also a handy setCallback function for JSONP.

对于JSONP,还有一个方便的setCallback函数。

#3


13  

Since Symfony 3.1 you can use JSON Helper http://symfony.com/doc/current/book/controller.html#json-helper

由于Symfony 3.1,您可以使用JSON助手http://symfony.com/doc/current/book/controller.html# JSON - Helper。

public function indexAction()
{
// returns '{"username":"jane.doe"}' and sets the proper Content-Type header
return $this->json(array('username' => 'jane.doe'));

// the shortcut defines three optional arguments
// return $this->json($data, $status = 200, $headers = array(), $context = array());
}

#4


9  

To complete @thecatontheflat answer i would recommend to also wrap your action inside of a try ... catch block. This will prevent your JSON endpoint to break on exceptions. Here's the skeleton I use:

为了完成@ thec赎罪的答案,我建议你在尝试的时候把你的行动包装起来……catch块。这将防止您的JSON端点中断异常。这是我使用的骨架:

public function someAction()
{
    try {

        // Your logic here...

        return new JsonResponse([
            'success' => true,
            'data'    => [] // Your data here
        ]);

    } catch (\Exception $exception) {

        return new JsonResponse([
            'success' => false,
            'code'    => $exception->getCode(),
            'message' => $exception->getMessage(),
        ]);

    }
}

This way your endpoint will behave consistently even in case of an errors and you will be able to treat them right on a client side.

这样,即使出现错误,您的端点也会始终保持一致,您将能够在客户端处理它们。

#5


7  

If your data is already serialized:

如果您的数据已经被序列化:

a) send a JSON response

a)发送一个JSON响应。

public function someAction()
{
    $response = new Response();
    $response->setContent(file_get_contents('path/to/file'));
    $response->headers->set('Content-Type', 'application/json');
    return $response;
}

b) send a JSONP response (with callback)

b)发送JSONP响应(带有回调)

public function someAction()
{
    $response = new Response();
    $response->setContent('/**/FUNCTION_CALLBACK_NAME(' . file_get_contents('path/to/file') . ');');
    $response->headers->set('Content-Type', 'text/javascript');
    return $response;
}

If your data needs be serialized:

如果您的数据需要被序列化:

c) send a JSON response

c)发送一个JSON响应。

public function someAction()
{
    $response = new JsonResponse();
    $response->setData([some array]);
    return $response;
}

d) send a JSONP response (with callback)

d)发送JSONP响应(带有回调)

public function someAction()
{
    $response = new JsonResponse();
    $response->setData([some array]);
    $response->setCallback('FUNCTION_CALLBACK_NAME');
    return $response;
}

e) use groups in Symfony 3.x.x

e)在Symfony 3.x.x中使用组。

Create groups inside your Entities

在实体内创建组。

<?php

namespace Mindlahus;

use Symfony\Component\Serializer\Annotation\Groups;

/**
 * Some Super Class Name
 *
 * @ORM    able("table_name")
 * @ORM\Entity(repositoryClass="SomeSuperClassNameRepository")
 * @UniqueEntity(
 *  fields={"foo", "boo"},
 *  ignoreNull=false
 * )
 */
class SomeSuperClassName
{
    /**
     * @Groups({"group1", "group2"})
     */
    public $foo;
    /**
     * @Groups({"group1"})
     */
    public $date;

    /**
     * @Groups({"group3"})
     */
    public function getBar() // is* methods are also supported
    {
        return $this->bar;
    }

    // ...
}

Normalize your Doctrine Object inside the logic of your application

在应用程序的逻辑中规范化您的Doctrine对象。

<?php

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
// For annotations
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;

...

$repository = $this->getDoctrine()->getRepository('Mindlahus:SomeSuperClassName');
$SomeSuperObject = $repository->findOneById($id);

$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer($classMetadataFactory);
$callback = function ($dateTime) {
    return $dateTime instanceof \DateTime
        ? $dateTime->format('m-d-Y')
        : '';
};
$normalizer->setCallbacks(array('date' => $callback));
$serializer = new Serializer(array($normalizer), array($encoder));
$data = $serializer->normalize($SomeSuperObject, null, array('groups' => array('group1')));

$response = new Response();
$response->setContent($serializer->serialize($data, 'json'));
$response->headers->set('Content-Type', 'application/json');
return $response;

#1


174  

Symfony 2.1

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

Symfony 2.2和更高版本

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

您有特殊的JsonResponse类,它将数组序列化为JSON:

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

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

但是如果您的问题是如何序列化实体,那么您应该看看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 *:

您还应该检查*上类似的问题:

#2


54  

Symfony 2.1 has a JsonResponse class.

Symfony 2.1有一个JsonResponse类。

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

The passed in array will be JSON encoded the status code will default to 200 and the content type will be set to application/json.

在数组中传递的将是JSON编码的状态码将默认为200,内容类型将被设置为application/ JSON。

There is also a handy setCallback function for JSONP.

对于JSONP,还有一个方便的setCallback函数。

#3


13  

Since Symfony 3.1 you can use JSON Helper http://symfony.com/doc/current/book/controller.html#json-helper

由于Symfony 3.1,您可以使用JSON助手http://symfony.com/doc/current/book/controller.html# JSON - Helper。

public function indexAction()
{
// returns '{"username":"jane.doe"}' and sets the proper Content-Type header
return $this->json(array('username' => 'jane.doe'));

// the shortcut defines three optional arguments
// return $this->json($data, $status = 200, $headers = array(), $context = array());
}

#4


9  

To complete @thecatontheflat answer i would recommend to also wrap your action inside of a try ... catch block. This will prevent your JSON endpoint to break on exceptions. Here's the skeleton I use:

为了完成@ thec赎罪的答案,我建议你在尝试的时候把你的行动包装起来……catch块。这将防止您的JSON端点中断异常。这是我使用的骨架:

public function someAction()
{
    try {

        // Your logic here...

        return new JsonResponse([
            'success' => true,
            'data'    => [] // Your data here
        ]);

    } catch (\Exception $exception) {

        return new JsonResponse([
            'success' => false,
            'code'    => $exception->getCode(),
            'message' => $exception->getMessage(),
        ]);

    }
}

This way your endpoint will behave consistently even in case of an errors and you will be able to treat them right on a client side.

这样,即使出现错误,您的端点也会始终保持一致,您将能够在客户端处理它们。

#5


7  

If your data is already serialized:

如果您的数据已经被序列化:

a) send a JSON response

a)发送一个JSON响应。

public function someAction()
{
    $response = new Response();
    $response->setContent(file_get_contents('path/to/file'));
    $response->headers->set('Content-Type', 'application/json');
    return $response;
}

b) send a JSONP response (with callback)

b)发送JSONP响应(带有回调)

public function someAction()
{
    $response = new Response();
    $response->setContent('/**/FUNCTION_CALLBACK_NAME(' . file_get_contents('path/to/file') . ');');
    $response->headers->set('Content-Type', 'text/javascript');
    return $response;
}

If your data needs be serialized:

如果您的数据需要被序列化:

c) send a JSON response

c)发送一个JSON响应。

public function someAction()
{
    $response = new JsonResponse();
    $response->setData([some array]);
    return $response;
}

d) send a JSONP response (with callback)

d)发送JSONP响应(带有回调)

public function someAction()
{
    $response = new JsonResponse();
    $response->setData([some array]);
    $response->setCallback('FUNCTION_CALLBACK_NAME');
    return $response;
}

e) use groups in Symfony 3.x.x

e)在Symfony 3.x.x中使用组。

Create groups inside your Entities

在实体内创建组。

<?php

namespace Mindlahus;

use Symfony\Component\Serializer\Annotation\Groups;

/**
 * Some Super Class Name
 *
 * @ORM    able("table_name")
 * @ORM\Entity(repositoryClass="SomeSuperClassNameRepository")
 * @UniqueEntity(
 *  fields={"foo", "boo"},
 *  ignoreNull=false
 * )
 */
class SomeSuperClassName
{
    /**
     * @Groups({"group1", "group2"})
     */
    public $foo;
    /**
     * @Groups({"group1"})
     */
    public $date;

    /**
     * @Groups({"group3"})
     */
    public function getBar() // is* methods are also supported
    {
        return $this->bar;
    }

    // ...
}

Normalize your Doctrine Object inside the logic of your application

在应用程序的逻辑中规范化您的Doctrine对象。

<?php

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
// For annotations
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;

...

$repository = $this->getDoctrine()->getRepository('Mindlahus:SomeSuperClassName');
$SomeSuperObject = $repository->findOneById($id);

$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer($classMetadataFactory);
$callback = function ($dateTime) {
    return $dateTime instanceof \DateTime
        ? $dateTime->format('m-d-Y')
        : '';
};
$normalizer->setCallbacks(array('date' => $callback));
$serializer = new Serializer(array($normalizer), array($encoder));
$data = $serializer->normalize($SomeSuperObject, null, array('groups' => array('group1')));

$response = new Response();
$response->setContent($serializer->serialize($data, 'json'));
$response->headers->set('Content-Type', 'application/json');
return $response;