【问题标题】:How can I get data from mysql database with json encode (Symfony 4)?如何使用 json 编码(Symfony 4)从 mysql 数据库中获取数据?
【发布时间】:2018-12-20 10:56:44
【问题描述】:

现在我正在通过 Doctrine 从数据库中获取数据:

$articles = $this->getDoctrine()->getRepository(Article::class)->findAll();
return $this->render('homepage.html.twig', array('articles' => $articles));

这工作正常。但我需要的是通过 json 编码获取数据,因为我想使用服务器端处理数据表。所以我尝试使用序列化器

  $encoders = array(new XmlEncoder(), new JsonEncoder());
  $normalizers = array(new ObjectNormalizer());

  $serializer = new Serializer($normalizers, $encoders);
  $articles = $this->getDoctrine()->getRepository(Article::class)->findAll();
  $jsonContent = $serializer->serialize($articles, 'json');

  return $this->render('homepage.html.twig', $jsonContent);

但我收到错误消息:

参数 2 传递给 Symfony\Bundle\FrameworkBundle\Controller\AbstractController::render() 必须是数组类型,给定字符串,调用 /Users/work/project/src/Controller/ArticleController.php 第 46 行 未捕获的 PHP 异常 Symfony\Component\Debug\Exception\FatalThrowableError:“参数 2 传递给 Symfony\Bundle\FrameworkBundle\Controller\AbstractController::render() 必须是数组类型,给定字符串,调用 /Users/work/project/src/Controller/ArticleController.php 第 46 行" 在 /Users/work/project/vendor/symfony/framework-bundle/Controller/ControllerTrait.php 第 219 行

【问题讨论】:

  • 您可以通过简单的方法来完成此操作,并发送至return $this->render('homepage.twig.html', [$jsonContent]);。这也是这个捆绑包的作用:omines.github.io/datatables-bundle
  • @Loek Wooow,这就是我一直在寻找的东西......
  • @Loek 你安装过这个包吗?我尝试安装它但收到错误消息:stackoverflow.com/questions/51303702/…

标签: php json symfony doctrine server-side


【解决方案1】:

所以将render 的第二个参数设为数组:

return $this->render('homepage.html.twig', ['json_content' => $jsonContent]);

在模板中:

{{ json_content }}

虽然我不知道你为什么使用模板,因为有一个 json() 方法返回单个 json:

return $this->json($articles); // without using serializer

【讨论】:

  • 你也可以使用twig函数对东西进行json_encode:{{ articles|json_encode }}
猜你喜欢
  • 2015-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2014-10-10
  • 2018-07-07
  • 1970-01-01
相关资源
最近更新 更多