在 Symfony2 中通过 ajax 提交表单

submit form by ajax in Symfony2

我有操作,首先需要通过 ajax 呈现表单,然后需要更新现有值。我已经得到了具有正确值的渲染表单,但是当我通过 ajax 单击提交表单时,我无法阻止表单提交,我有这个脚本:

 $('#edit-comment').click(function (e) {
    e.preventDefault();
    console.log(1);
});

但是提交仍然有效!我做错了什么。而且我不知道我需要如何在编辑操作中处理提交的表单。这是它的现有部分:

 /**
 * @Route("/edit/comment", name="chat_edit", options={"expose"=true})
 */
public function editAction(Request $request)
{
    $comment_id = json_decode($request->getContent(), true)['commentId'];
    $comment = $this->get('comment.repository')->find($comment_id);
    $form = $this->createForm(new CommentType(), $comment);

    return $this->render("ChatCommentBundle:Comment:form.html.twig",
        array('form' => $form->createView())
    );
}

Link 到 gist with form type

更新:

原来的答案(下面)仍然适用,但考虑到表单实际上是使用 AJAX 加载的,您不能在 $(document).ready 回调中绑定事件侦听器。对您来说最好的选择是使用事件委托。这是通过将事件侦听器附加到 DOM 元素来完成的,该元素 does 从一开始就存在,但让该侦听器为以后可能添加的元素拾取事件。例如:body 元素会一直存在,所以你可以在那里监听一个表单提交,那个表单是否存在并不重要:

$('body').on('submit', '#form-id', function(e)
{
    console.log('#form-id was submitted, do AJAX => submission stopped');
    return false;
    //or
    e.preventDefault();
    e.stopPropagation();
});

很好地解释了为什么以及如何工作 here。归结为所有事件都通过目标节点的所有父 DOM 元素这一事实,因此您可以在 DOM 中的任何位置附加侦听器,并在事件到达目标之前对其进行处理。
我认为 this old answer of mine 也可以解释一件事或两件事。它不使用 jQ,但包含 jQ 内部用于委托的代码的简化版本。


您正在阻止 $('#edit-comment') 上单击事件的默认效果,但该事件仍会传播到表单。您可能还想添加 e.stopPropagation()。或者只是回调中的 return false;(这会阻止默认的 停止传播)。

但是,防止提交表单的更好方法是使用 submit 事件,并在那里停止提交:

$('#form-id').on('submit', function(e)
{
    console.log('Do ajax call here');
    return false;
    //or
    e.preventDefault();
    e.stopPropagation();
});