Pulling records from database to javascript by Symfony2 controller

假装没事ソ 提交于 2021-02-08 08:43:20

问题


Im trying to fetch categories list from my database and put it in my javascript code so i can use it later. But I've encountered problems with this task - after returning this list to javascript - they are empty.

Here is my symfony2 controller action code:

public function fetchCategoriesAction(){
     $categories = $this->getDoctrine()->getRepository('MyDataBundle:Category')->findAll();
     $return=array("responseCode"=>200,  "categories"=>$categories);
     $return=json_encode($return);//jscon encode the array
     return new Response($return,200,array('Content-Type'=>'application/json'));
}

Here is my js code:

var categories;

function categoriesLoad(){

var url=$("#categories_fetch").val(); //link to my controller

$.post(url,function(data){

     if(data.responseCode==200 ){           
         categories = data.categories;
         console.log(categories);
     }else{
       console.log("An unexpeded error occured.");
    }
});

}

I'm running $(document).ready(function() { categoriesLoad(); });

But then after using console.log(categories) I'm getting empty objects, although their number match the number of records in the database.

I'm just starting programming in symfony2 and I'd appreciate any help :)

EDIT:

SOLVED

I've just changed my controller action code. Here it is updated:

public function fetchCategoriesAction(){

    $encoders = array(new XmlEncoder(), new JsonEncoder());
    $normalizers = array(new GetSetMethodNormalizer());
    $serializer = new Serializer($normalizers, $encoders);

    $em = $this->getDoctrine()->getManager();
    $categories = $em->createQuery(
            'SELECT u
            FROM MyDataBundle:Category u'
    )->getResult();

    $categories = $serializer->serialize($categories, 'json');
    $return=array("responseCode"=>200,  "categories"=>$categories);
    $return=json_encode($return);
    return new Response($return,200,array('Content-Type'=>'application/json'));
}

Now it works fine. Thanks to @Pawel and @SAM


回答1:


My example: PHP function:

public function getDistrictListAction($id) {

        $em = $this->getDoctrine()->getManager();

        $query = $em->createQuery(
           // DQL
        );

        return new JsonResponse($query->getArrayResult());
    }

JS Code:

var dropdown = $('.dropdown-selector');
dropdown.change( function() {
    $.ajax({
         url: 'url_to_function'
         beforeSend: function() {
              dropdown.attr('disabled', true);
         },
         success: function(data) {
              dropdown.find('option').not('[value=]').remove();
              $.each( JSON.parse(data), function(key, value) {
                   dropdown.append( $( "<option></option>" ).attr( "value", value.id ).text( value.name ));
              });
              dropdown.attr('disabled', false);
         }
    });
}

This you can set on change event for example as a callback. Before send you make dropdown disabled, and after load via AJAX option you are enabale it again.



来源:https://stackoverflow.com/questions/17994748/pulling-records-from-database-to-javascript-by-symfony2-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!