如何在symfony2控制器中发送json响应 [英] How can i send json response in symfony2 controller

查看:316
本文介绍了如何在symfony2控制器中发送json响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

Data is entering correctly in database.

但我不知道是否需要将一些JSON发送回jQuery。实际上我对JSON事情感到困惑。

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

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

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.

我很困惑如何获取数据

这是我当前的代码

$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

推荐答案

Symfony 2.1

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

return $response;






Symfony 2.2 和更高

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

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

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






但如果您的问题是如何序列化实体然后你应该看看 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);

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

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

这篇关于如何在symfony2控制器中发送json响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆