Symfony2 returns empty JSON on AJAX call while var

2019-02-10 01:10发布

Problem

I'm trying to get an AJAX response so I can fiddle around with it to make my forms easier to use. When I make the controller (code below) return a normal response with var_dump(), I get the object's output so I know the query isn't wrong (I'm using ID 1 to query to debug). However, when I return the output with json_encode(), I just get an empty JSON file.

HTML form in the view

<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 in the same view

<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>

Controller with normal response (works)

public function ajaxAction()
{

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

    $output = var_dump($location);

    return $output;
}

Controller with AJAX response (doesn't work, returns empty JSON)

public function ajaxAction()
{

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

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

Could anyone help me out here, please? This is driving me nuts!

4条回答
欢心
2楼-- · 2019-02-10 01:27

I managed to fix it by using Doctrine2's entity manager to get the result in an array, after which I proceeded to encode it into JSON. I'm not sure if this is the cleanest way to do it (getEntityManager() seems to be deprecated according to my IDE) but it works fine for now.

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);
}
查看更多
迷人小祖宗
3楼-- · 2019-02-10 01:31

If you want to get back data, you have to use a query repository (dsl) and on your $query variable use the getArrayResult() method. That allows you to get an array directly.

查看更多
甜甜的少女心
4楼-- · 2019-02-10 01:42

Code example:

$entity = // Get some entity
$result = array(
    'id' => $entity->getId(),
    'name' => $entity->getName()
);

return new Response(json_encode($result));
查看更多
Luminary・发光体
5楼-- · 2019-02-10 01:43

This is happening because json_encode() does not know how to serialize an object (other than StdClass) to JSON. There are at least two ways to solve this:

  1. If you are on PHP 5.4 or above, you can have your object implement JsonSerializable, which PHP will use when you call json_encode() on the object.
  2. If you are on PHP 5.3 or earlier, you can use Symfony's Serializer component to convert the object to JSON using a number of different methods. I won't explain how exactly to do that, since the documentation is pretty clear.
查看更多
登录 后发表回答