Jquery.submit不会拦截表单提交


Jquery .submit wont intercept form submission

我有php代码,它回声了另一个jquery代码插入到我的html中的表单。这一切都很好。我正在尝试使用ajax提交此表单。

echo '<form id="comment_form" action="commentvalidation.php?PhotoID='.$_GET['PhotoID'].'" method="POST">';
echo '<label>Comment: </label>';
echo '<textarea id="description" name="CommentDesc" cols="25" rows="2"></textarea>';
echo '<input class="button" id="comment_btn" type="submit" name="Comment" value="Comment" >';
echo '</form>';

传统上提交表单时效果良好。问题是我无法用ajax提交它。.submit不会阻止默认操作。

<script>
$(function(){
        $('#comment_form').submit(function() {
          alert("we are in");
                    $.post($('#comment_form').attr('action'), $('#comment_form').serialize(), function(data){
                        $('#comment_form').html("<div id='message'></div>");
                    });
            //Important. Stop the normal POST
            return false;
        });
});
</script>

您可能在表单进入页面之前绑定了submit事件处理程序。使用事件委派而不是直接绑定,例如

$(document.body).on('submit', '#comment_form', function(e) {
    e.preventDefault();
    alert('We are in');
    // and the rest, no need for return false
});

作为一个附录,尽量不要从PHP中回声出大块的HTML。如果你只是在需要时切换到PHP上下文,例如,它的可读性更强,而且你不太可能遇到引号和串联的问题

// break out of the PHP context
?>
<form id="comment_form" action="commentvalidation.php?PhotoID=<?= htmlspecialchars($_GET['PhotoID']) ?>" method="POST">
<label>Comment: </label>
<textarea id="description" name="CommentDesc" cols="25" rows="2"></textarea>
<input class="button" id="comment_btn" type="submit" name="Comment" value="Comment" >
</form>
<?php
// and back to PHP

问题似乎来自于form that was inserted into my html by another jquery code。根据我的理解,表单是在页面加载后动态创建的。

在这种情况下,当执行submit处理程序注册代码时,元素不存在于dom结构中,这意味着处理程序从未注册到表单中。

尝试使用委托的事件处理程序来解决此

$(function(){
        $(document).on('submit', '#comment_form', function() {
          alert("we are in");
                    $.post($('#comment_form').attr('action'), $('#comment_form').serialize(), function(data){
                        $('#comment_form').html("<div id='message'></div>");
                    });
            //Important. Stop the normal POST
            return false;
        });
});

演示:问题
演示:解决方案