dsg435665475 2014-09-08 21:30
浏览 71
已采纳

从ajaxcontroller symfony返回json

i try to view some rows from a table. I have one AjaxController in Symfony, this controller have the following function:

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:

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.

I dont use a repository. I only using the basic functions from symfony.

  • 写回答

2条回答 默认 最新

  • dtef9322 2014-09-08 21:37
    关注

    Use the built-in JsonResponse class to return a JSON response. So in your getPlaceList controller action, add something like this at the end:

    use Symfony\Component\HttpFoundation\JsonResponse;
    
    ...
    
    return new JsonResponse(array('place' => $placeEntity));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题