Javascript 如何在 symfony2 控制器中发送 JSON 响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11714941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I send JSON response in symfony2 controller
提问by Mirage
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.
这只是带有成功消息的模板。
回答by Vitalii Zurian
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.2and higher
Symfony 2.2及更高版本
You have special JsonResponseclass, which serialises array to JSON:
您有特殊的JsonResponse类,它将数组序列化为 JSON:
return new JsonResponse(array('name' => $name));
But if your problem is How to serialize entitythen 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 StackOverflow:
您还应该检查 StackOverflow 上的类似问题:
回答by jmaloney
Symfony 2.1 has a JsonResponseclass.
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.
setCallback
JSONP还有一个方便的函数。
回答by Bettinz
Since Symfony 3.1 you can use JSON Helper http://symfony.com/doc/current/book/controller.html#json-helper
从 Symfony 3.1 你可以使用 JSON Helper 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());
}
回答by Slava Fomin II
To complete @thecatontheflat answer I would recommend to also wrap your action inside of a try … catch
block. This will prevent your JSON endpoint from breaking on exceptions. Here's the skeleton I use:
要完成@thecatontheflat 的回答,我建议还将您的操作包装在一个try … 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 errors and you will be able to treat them right on a client side.
这样,即使在出现错误的情况下,您的端点也能保持一致的行为,并且您将能够在客户端正确对待它们。
回答by Avram Cosmin
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.xx 中使用组
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;