Symfony2 在 AJAX 调用上返回空 JSON,而变量不为空

2023-11-22

Problem

我正在尝试获取 AJAX 响应,以便我可以摆弄它以使我的表单更易于使用。当我使控制器(下面的代码)返回正常响应时var_dump(),我得到了对象的输出,所以我知道查询没有错误(我使用 ID 1 来查询以进行调试)。但是,当我返回输出时json_encode(),我只得到一个空的 JSON 文件。

视图中的 HTML 表单

<div id="content">
    <form id="myForm" action="{{path('snow_ajax')}}" method="POST" >
        Write your name here:
        <input type="text" name="name" id="name_id" value="" /><br />
        <input type="submit" value="Send" />
    </form>
</div>

同一视图中的脚本

<script type="text/javascript">
    $(document).ready(function() {

        $("#myForm").submit(function(){
            var url=$("#myForm").attr("action");

            $.post(url,{
                formName:"ajaxtest",
                other:"attributes"
            },function(data){

                if(data.responseCode==200 ){
                    alert("Got your json!");
                }
                else{
                    alert("something went wrong :(");
                }
            });
            return false;
        });
    });
</script>

控制器响应正常(工作)

public function ajaxAction()
{

    $location = $this->getDoctrine()->getRepository('SnowFrontBundle:Location')
        ->find(1);

    $output = var_dump($location);

    return $output;
}

具有 AJAX 响应的控制器(不起作用,返回空 JSON)

public function ajaxAction()
{

    $location = $this->getDoctrine()->getRepository('SnowFrontBundle:Location')
        ->find(1);

    return new Response(json_encode($location), 200);
}

请问有人可以帮我吗?这让我抓狂!


我设法通过使用 Doctrine2 的实体管理器将结果获取到数组中来修复它,然后我继续将其编码为 JSON。我不确定这是否是最干净的方法(根据我的 IDE, getEntityManager() 似乎已被弃用),但目前它工作正常。

public function ajaxAction()
{
    $em = $this->getDoctrine()->getEntityManager();
    $query = $em->createQuery('SELECT l FROM Snow\FrontBundle\Entity\Location l WHERE l.id=:id');
    $query->setParameter('id', 1);
    $result = $query->getArrayResult();

    return new Response(json_encode($result), 200);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Symfony2 在 AJAX 调用上返回空 JSON,而变量不为空 的相关文章

随机推荐