【问题标题】:As returning a response to a ajax symfony 2?作为对 ajax symfony 2 的响应?
【发布时间】:2015-08-10 00:02:30
【问题描述】:

我有一个非常简单的系统,普通用户,黄金用户。起初它只是简单地在 routing.yml 中创建了一个路径,我将函数寻址到执行操作并返回相同的视图并完美运行。现在实现 ajax 以加快进程。 当我点击按钮向上时,运行Ajax,控制器的指定路径将我引导至相关动作,全部成功执行,但在返回同一视图时,无法正常工作。 Ajax 采取错误路径,并由我编写的警报屏幕打印。总之,一切正常,直到我不得不返回 Ajax 操作。

listarUsuariosParaAscender.html.twig

    //..some code..//
    <p id="{{ usuario.id }}" >Ascender a Usuario Gold</p>
    //..some code..//

    {% block javascripts %}
        {{ parent() }}
        <script type="text/javascript" src=" {{ asset('bundles/MICARPETA/js/jquery-2.1.4.min.js') }} "></script>
        <script type="text/javascript">

        $(document).ready(function(e) {

            $("p").click(function(e){
                var id = $(this).attr('id');
            $.ajax({
                                type: "POST",
                                url: "{{ path('ascender_a_gold') }}",
                                data: { 'id' : ' ' + id + ' ' },
                                error: function(){
                                      alert("Error petición ajax");
                                },
                                success: function(data){                                                    

                                      alert(data);

                                }
                    });
            });
        });
        </script> 

{% endblock %}

routing.yml

ascender_a_gold:
    pattern: /admin/ascenderAGold
    defaults: { _controller: ProyectoAdminBundle:Admin:ascenderAGold }

AdminController.php

public function ascenderAGoldAction(){
        $id = $_POST['id'];
        $em = $this->getDoctrine()->getManager();
        $user = new User();
        $roleviejo = new Role();
        $rolenuevo = new Role();
        $usuario = $em->getRepository('AtajoBundle:User')->findOneUser($id);
        $roleviejo = $em->getRepository('ProyectoSeguridadBundle:Role')->findByRoleJoinUsuario($id);
        $rolenuevo = $em->getRepository('ProyectoSeguridadBundle:Role')->findByRole('ROLE_USER_GOLD');

        $usuario->setRoles($rolenuevo);

        $em->persist($usuario);
        $em->flush();

        //Until here everything works well , when I have to return to Ajax , ajax it takes the path of 'error'    

        $data = 'hello';

        return new JsonResponse(array('data' => $data)); 
        }

【问题讨论】:

  • 检查浏览器开发工具网络中的实际请求以查看状态和返回的内容(如果有)。还为`$.ajax 设置dataType:'json'
  • 你为什么使用$_POST而不是symfony的Request对象?

标签: javascript php jquery ajax symfony


【解决方案1】:

你的控制器的最后两行没有错,所以不应该有错误。唯一可能缺少的是包括 JsonResponse 类。你的控制器顶部有以下使用语句吗?

use Symfony\Component\HttpFoundation\JsonResponse

【讨论】:

    猜你喜欢
    • 2016-05-03
    • 2016-12-29
    • 2015-09-13
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    相关资源
    最近更新 更多