php - Symfony2 重新提交表单时转发

标签 php jquery ajax forms symfony

当我第二次在服务器上发送包含数据的表单时,它会将我重定向到处理客户端请求的路由。

我的意思

我有一个 Controller 方法,它接受来自客户端的 AJAX 请求并验证数据

public function addCommentAction(Request $request)
    {
        $post = new Post();
        $form = $this->createForm(new PostType(), $post);
        $post->setCreated(new \DateTime('now'));
        if ($request->getMethod() == 'POST') {
            $form->submit($request);
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $em->persist($post);
                $em->flush();
                $this->get('session')->getFlashBag()->add('success', 'Comment has been sent on moderation. Wait 1 minute before send another comment.');
            }
        }
        return $this->render('GuestbookBundle:Post:postForm.html.twig', array(
            'form' => $form->createView(),
        ));
    }

我的 Ajax 。序列化表单,然后使用表单中的数据向服务器发送请求

$('.container .form-comment .send-comment').on('click', function(e) {
        var $from = $(this).closest('form');
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: $from.attr('action'),
            data: $from.serialize(),
            success: function(data) {
                $('.form-comment').empty().append(data);
            }
        })
    });

当我第二次单击“发送”按钮时,它会将我重定向到页面 mydomain.com/add,该页面处理来自表单的请求

add:
    path:     /add
    defaults: { _controller: GuestbookBundle:Post:addComment }
    requirements:
        _method:  POST

如何解决这个问题?为什么成功发送后我的表格不清楚?

谢谢。

最佳答案

首先,您在提交后再次返回表单,为什么需要这个? 据我所知,您正在尝试添加评论,因此提交后您可以返回消息(例如 - 成功)或您需要的任何其他数据。

    public function addCommentAction(Request $request)
    {
        $post = new Post();
        $form = $this->createForm(new PostType(), $post);
        $result = ['status' => 'success',
                'comment' => 'Comment has been sent on moderation. Wait 1 minute before send another comment.' ];
        $post->setCreated(new \DateTime('now'));
        if ($request->getMethod() === 'POST') {
            $form->submit($request);
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $em->persist($post);
                $em->flush();
//              $this->get('session')->getFlashBag()->add('success', 'Comment has been sent on moderation. Wait 1 minute before send another comment.');
                return new JsonResponse($result);
            } 
            $result['status'] = 'error';
            return new JsonResponse($result);
        }
        return $this->render('GuestbookBundle:Post:postForm.html.twig', array(
            'form' => $form->createView(),
        ));
    }

JavaScript:

$('.container .form-comment .send-comment').on('click', function(e) {
        var $from = $(this).closest('form');
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: $from.attr('action'),
            data: $from.serialize()

        }).done(function(data) {
                  //data will contains data.status && data.message
                  //you can add any data in your controller

            $('.form-comment').empty().append(data.messages);

        }).fail(function(data) {
            alert(data.messages);
        });
    });

您还使用了已弃用的语法, 最好使用 $form->handleRequest($request);,你可以阅读 here

关于php - Symfony2 重新提交表单时转发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28982190/

相关文章:

javascript - 提交表单时将 div 滚动到顶部

javascript - 如何在更改 select 的值时显示/隐藏文本框

javascript - 第二个下拉列表取决于我的第一个下拉列表。如何?

javascript - 获取 Laravel Controller 中的 Js 值

php - 为什么我的 .htaccess 在部署时停止工作

php - 选择查询的顺序在准备好的语句中不起作用

php - 在引导模式中将 ajax 成功数据显示为数据表

php - Laravel Web-socket 和 Chrome `SameSite` 属性

jquery - Fancybox 2 可见的导航箭头

javascript - jQuery Ajax 在 PhantomJS 中不起作用