symfony 使用 json ajax 响应

问题描述 投票:0回答:2

我是 Symfony 的新手,我想做一些操作,这样我可以通过 Ajax 获取实体主题中所有元素的列表,但答案仍然是“未定义”这里的代码文本很强大

vue

    $(document).ready(function () {
        var $theme = $('#theme');
        $theme.append('<option value="">Choisir un thème</option>');
        $.ajax({
            type: 'post',
            url: '{{ path('web_site_liste_theme_cmb') }}',
            dataType: 'json',
            beforeSend: function () {
                $('#themediv').append('<div id="loading" style=" float: left; display: block;"><img src="{{ asset('bundles/BackBundle/img/loadingicon.gif') }}"/></div>');
            },
            success: function (json) {
                {#$('#theme').append({{  dump(json)}});#}
                console.log(json.value);
                $.each(json, function (index, value) {

                    //console.log(value);
                    $('#theme').append('<option value="' + value.id + '">' + value.name + '</option>');
                    $('#loading').remove();
                });
            }
        });
    });

控制器

  public function ListeThemeAction(Request $request)
{

    $em = $this->getDoctrine()->getEntityManager();
    if ($request->isXmlHttpRequest()) {
        $themes = $em->getRepository('WebSiteBackBundle:theme');
        $themes = $themes->findAll();
        //var_dump($themes);

        return  new JsonResponse($json);
    }
    return new JsonResponse('no results found', Response::HTTP_NOT_FOUND); // constant for 404

}

服务器响应是 200 OK,一切似乎都正常,我在数据库中有相同数量的数据,但我无法读取对象值

这是: console.log(json)

php ajax symfony model-view-controller
2个回答
5
投票

有很多方法可以做到这一点;我将向您展示其中之一。

首先,准备数据以从控制器发送并返回

JsonResponse
实例:

public function fooAction()
{
    $data = ['foo1' => 'bar1', 'foo2' => 'bar2'];

    return new JsonResponse($data); // or $this->json($data) since Symfony 3.1
}

JsonResponse
告诉浏览器发送的数据必须解释为JSON;否则,这些数据默认被解释为纯文本。

其次,使用相同的数据结构通过 JavaScript 回调函数访问它:

$.post('{{ path('web_site_liste_theme_cmb') }}', function (data) {
    console.log(data['foo1']); // output: bar1
    console.log(data.foo2);    // output: bar2 
});

在你的问题中,你发送的数据是一个对象数组,所以你需要查看这个变量“json”(数组)并访问该对象的每个属性。


3
投票

好吧,我找到了答案,我必须更改控制器才能实现它。 谢谢约内尔! 这是一个帮助我的链接控制器中的 Json

控制器

public function ListeThemeAction(Request $request)
{
$output=array();
    $em = $this->getDoctrine()->getEntityManager();
    if ($request->isXmlHttpRequest()) {
        $themes = $em->getRepository('WebSiteBackBundle:theme');
        $themes = $themes->findAll();
        foreach ($themes as $theme){

            $output[]=array($theme->getId(),$theme->getName());
        }
     /*   var_dump($themes);
        $json = json_encode($themes);

        $response = new Response();*/
        //            return $response->setContent($json);
        return new JsonResponse($output);

    }
    return new JsonResponse('no results found', Response::HTTP_NOT_FOUND);
}

Vue

        $(document).ready(function () {
        var $theme = $('#theme');
        $theme.append('<option value="">Choisir un thème</option>');
        $.ajax({
            type: 'post',
            url: '{{ path('web_site_liste_theme_cmb') }}',
            dataType: 'json',
            beforeSend: function () {
                $('#themediv').append('<div id="loading" style=" float: left; display: block;"><img src="{{ asset('bundles/BackBundle/img/loadingicon.gif') }}"/></div>');
            },
            success: function (json) {

                console.log(json);
                $.each(json, function (index, value) {

                    //console.log(value);
                    $('#theme').append('<option value="' + value[0]+ '">' + value[1] + '</option>');
                    $('#loading').remove();
                });
            }
        });
    });

希望它能帮助别人。谢谢大家的回答,对我帮助很大

© www.soinside.com 2019 - 2024. All rights reserved.