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

查看:24
本文介绍了如何在 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.

我很困惑如何取回这些数据.

I am confused how can get that data back.

这是我当前的代码:

$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:

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

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