简体   繁体   English

通过Symfony2控制器将记录从数据库中提取到javascript

[英]Pulling records from database to javascript by Symfony2 controller

Im trying to fetch categories list from my database and put it in my javascript code so i can use it later. 我试图从我的数据库中获取类别列表,并将其放入我的javascript代码中,以便以后使用。 But I've encountered problems with this task - after returning this list to javascript - they are empty. 但是我在执行此任务时遇到了问题-在将此列表返回给javascript之后-它们为空。

Here is my symfony2 controller action code: 这是我的symfony2控制器动作代码:

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: 这是我的js代码:

var categories; var类别;

function categoriesLoad(){ 函数categoryLoad(){

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(); }); 我正在运行$(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. 但是然后在使用console.log(categories)之后,我得到了空的对象,尽管它们的数量与数据库中的记录数匹配。

I'm just starting programming in symfony2 and I'd appreciate any help :) 我刚刚开始在symfony2中编程,非常感谢您的帮助:)

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 感谢@Pawel和@SAM

My example: PHP function: 我的示例:PHP函数:

public function getDistrictListAction($id) {

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

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

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

JS Code: JS代码:

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. 在发送之前,请禁用下拉菜单,在通过AJAX选项加载后,请再次启用下拉菜单。

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

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