【问题标题】:Symfony: cannot fetch all the rows in a table via jsonresponseSymfony:无法通过 jsonresponse 获取表中的所有行
【发布时间】:2023-03-31 21:22:01
【问题描述】:

我正在尝试通过 jsonresponse 将“产品”表中的所有记录提取到我的 ajax 脚本中,该脚本可以进一步加载到我的 twig 模板中,但到目前为止,json 返回的值为 null,

以下是我的控制器:

public function showAction($slug){
    $em = $this->getDoctrine()->getManager();
        if($slug == 'prod'){
            $repo = $em->getRepository('SystemBundle:Products');
            $q = $repo->createQueryBuilder('u');
            return new JsonResponse($q);
        }

}

以下是我的 ajax 函数:

<script>
    function fetchprod() {
        $.ajax({
            url: "/show/prod",
            dataType: "json"
        }).success(function(data){
            $('#contaiber').html(JSON.stringify(data.sum));
        });
    }
    fetchprod()
    setInterval(function () {fetchprod()}, 3000);
</script>

这是我的标记(只是一个容器 div 来查看返回的内容):

<div id="container">

</div>

我在 div 中没有得到任何东西,但是当我输入 url 时,我可以看到页面上显示“{}”(基本上是一个空白数组)。

我该如何解决这个问题? 谢谢

【问题讨论】:

    标签: php jquery ajax symfony


    【解决方案1】:

    试试这个

    $em = $this->getDoctrine()->getManager();
    if($slug == 'prod'){
        $repo = $em->getRepository('SystemBundle:Products');
        $q = $repo->createQueryBuilder('u')
        ->getQuery();
        $products = $q->getResult();
        return new JsonResponse($products);
    }
    

    【讨论】:

    • 输出:[{}],但还是一个空白数组!
    • 你在 $product 结果中得到了什么??您是否尝试使用 dump() 。可能没有数据从选定的表返回。
    【解决方案2】:

    $result = $q->getQuery()->getOneOrNullResult(); to get one record $result = $q->getQuery()->getResult(); to get all record 可能是您需要先获得结果,然后再通过 json 将其传回。

    【讨论】:

    • 我使用了 $result = $q->getResult();,我得到了 "[{}]" 作为输出!它仍然返回一个空白数组!
    【解决方案3】:

    试试这个:

    $em = $this->getDoctrine()->getManager();
        if($slug == 'prod'){
            $repo = $em->getRepository('SystemBundle:Products');
            $q = $repo->createQueryBuilder('u')
                ->getQuery()
                ->getArrayResult();
            return new JsonResponse($q);
        }
    

    简单,有效!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-14
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      • 2017-11-24
      • 2021-10-20
      相关资源
      最近更新 更多