简体   繁体   English

从ajaxcontroller symfony返回json

[英]return json from ajaxcontroller symfony

i try to view some rows from a table. 我尝试从表中查看一些行。 I have one AjaxController in Symfony, this controller have the following function: 我在Symfony中有一个AjaxController,该控制器具有以下功能:

use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Rowoco\AllgemeinBundle\Entity\Place;
use Symfony\Component\HttpFoundation\JsonResponse;
.
.
.

public function defaultAjaxAction( $job )
{
    $user = $this->get('security.context')->getToken()->getUser();
    $userId = $user->getId();
    $result = $this->$job( $userId );

    // Initialisiert Serializer
    $encoder = [new JsonEncoder()];
    $normalizer = [new GetSetMethodNormalizer()];
    $serializer = new Serializer($normalizer, $encoder);
    $newData = $serializer->serialize($result, 'json');

    return new Response($newData);
}

public function getPlacelist( $iduser )
{
    $em = $this->getDoctrine()->getManager();
    $request = Request::createFromGlobals();

    //if i put here a return 123, then the output in the javascript-console would return 123
    $placeRepo = $em->getRepository( "RowocoAllgemeinBundle:Place" );
    $placeEntity = $placeRepo->findBy(
        array(),
        array(),
        $request->request->get( "limitCount" ),
        $request->request->get( "limitStart" )
    );
    return new JsonResponse(array('place' => $placeEntity));
}

In my js-file i call it with this function: 在我的js文件中,我用以下函数调用它:

function getPlaces()
{
    var data = {};
    data['limitCount'] = 10;
    data['limitStart'] = 0;

    var url = $( "#pageparameter" ).data( "url-getplacelist" );

    $.ajax({
            type: "POST",
            url: url,
            data: data,
            dataType: "json"
        })
        .done(function(resp){
            console.log(resp);
            $( "#viewPlaces").html(resp.place.description);
        })
        .error(function(){
            console.log("No connection");
        });

}

In the table, i have 2 rows and see them in the workbench. 在表中,我有2行,并在工作台中看到它们。

I dont use a repository. 我不使用存储库。 I only using the basic functions from symfony. 我只使用symfony的基本功能。

Use the built-in JsonResponse class to return a JSON response. 使用内置的JsonResponse类返回JSON响应。 So in your getPlaceList controller action, add something like this at the end: 因此,在您的getPlaceList控制器操作中,在末尾添加以下内容:

use Symfony\Component\HttpFoundation\JsonResponse;

...

return new JsonResponse(array('place' => $placeEntity));

i dont know why i´m using all the time 我不知道为什么我一直都在用

$resp = array ( 
   "foo" => "bar"
);


return @json_decode(@json_encode($resp),1);

but it always works very nice 但它总是很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM