【发布时间】: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