gpt4 book ai didi

jquery - 在 Controller 中获取 json 答案

转载 作者:行者123 更新时间:2023-12-01 06:01:35 24 4
gpt4 key购买 nike

我正在努力修改网页中的实体(Symfony 没有什么不寻常的:))。我目前有一个应该修改的实体。我使用 Jeditable 进行该版本,而不是在版本之后立即修改实体,而是将修改后的元素存储在 json 中,当用户确认他的修改(通过模式对话框确认操作)时,我将该 JSON 发送到我的 Controller 。

那就是事情变得更糟的时候^^

我检查了 json 数组是否包含正确的信息。但是当我在 Controller 中拦截请求时,它似乎不包含我想要的内容。这是我的 Controller :

public function postorganisationAction(){
$modifFields = array();
$content = $this->get("request")->getContent();
$this->get('logger')->info('request123456 ');
if (!empty($content))
{
$modifFields = json_decode($content, true);
$repository = $this->getDoctrine()
->getEntityManager()
->getRepository('MyBundle:Organisation');
$organisation = $repository->findById($modifFields["id"]);
$organisation->setFromArray($modifFields);

$em = $this->getDoctrine()->getEntityManager();

$em->persist($organisation);

$em->flush();
}

}

setFromArray 函数获取一个包含 "name" => "newname" 等元素的数组。

当我尝试记录请求、内容或 $modifFields["id"](正如我所说,我检查了 JSON 中的 id 在 jquery 中是否正确)时,日志不会出现。

有人知道我做错了什么吗?

编辑:

经过一些修改(感谢 ManseUK),我能够:
- 获取 jQuery 函数来发送 JSON 字符串而不是数组 ( JSON.stringify(oModifFields); )
- 解决问题:我在使用 $organisation 时遇到了转换错误,然后我将其转换为所需类型的对象

就这样吧^^

最佳答案

Symfony2 有一些有用的类用于序列化和反序列化实体。

这是如何进行的:

  1. 定义一种将实体规范化为数组的方法,数组中的每一对键/值都将是 json 字符串中的键/值;
  2. 导入序列化程序,它将您的数组(规范化的实体)转换为 json 字符串、XML 文档或您想要的任何内容。

对于第一个操作(标准化你的实体),Symfony2 内置了两种可能性:

  • 在您的实体上实现 Symfony\Component\Serializer\Normalizer\NormalizesInterface。您必须填写两个方法,这两个方法会将您想要在 json 中看到的属性标准化为数组或非标准化为数组;
  • 创建您自己的 Normalizer 类,它将实现 Symfony\Component\Serializer\Normalizer\NormalizerInterface

在 Controller (或您将定义的服务)中,您将执行以下操作来对实体进行编码:

$serializer = new Symfony\Component\Serializer\Serializer(
array(
new Symfony\Component\Serializer\Normalizer\CustomNormalizer(), //if you implement NormalizableInterface
new YourOwnCustomNormalizer() //if you created your own custom normalizers
),
array(
'json' => new Symfony\Component\Serializer\Encoder\JsonEncoder()
)
);
$json = $serializer->serialize($yourEntity, 'json');
return new Response($json);

并从 json 字符串检索实体:

$jsonString = $content = $this->get("request")->get('yourString'); //please, check how you retrieve data from your request
$serializer = new Symfony\Component\Serializer\Serializer(
array(
new Symfony\Component\Serializer\Normalizer\CustomNormalizer(), //if you implement NormalizableInterface
new YourOwnCustomNormalizer() //if you created your own custom normalizers
),
array(
'json' => new Symfony\Component\Serializer\Encoder\JsonEncoder()
)
);
$entity = $serializer->deserialize($jsonString, '\namespace\to\your\entity', 'json');

关于jquery - 在 Controller 中获取 json 答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11010379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com