表单仍在preventDefault上提交 [英] Form still submits on preventDefault

查看:74
本文介绍了表单仍在preventDefault上提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery将表单数据提交到表单操作中的文件中.但是,当我提交表单时,浏览器将重定向到操作(comment.php).我不知道为什么这是因为e.preventDefault()应该停止浏览器的重定向.理想情况下,我希望浏览器不要重定向并保留在当前页面(index.php).

I am using jQuery to submit form data to a file in the form's action. However, when I submit the form, the browser redirects to the action (comment.php). I don't know why this is because e.preventDefault() should stop the browser's redirection. Ideally, I would like the browser to not redirect and remain on the current page (index.php).

jQuery:

<script type='text/javascript'>
    $('document').ready(function(){
        $('.commentContainer').load('../writecomment.php');
        $('.answerContainer').on('submit', 'form', function(e){
            e.preventDefault();
            var form = $(this).closest('form');
            $.post($(form).attr('action'), 
            $(form).serialize(), 
            function() {
                $('.commentContainer').load('../writecomment.php');
                $('.commentBox').val('');
            }
        });
    });
</script>

HTML表单:

<form method='POST' action='../comment.php'>
    //form contents
</form>

推荐答案

我认为您的selectoron方法无法正常工作.尝试:$('form').on('submit', function(e) {您确定已将表单包裹在具有answerContainer ??

I don't think your selector and on method is working correctly. Try: $('form').on('submit', function(e) { are you sure you have wrapped your form in a element with the class answerContainer??

,然后确保不要使用$.post使用$.ajax:

and then just to be sure don't use $.post use $.ajax:

this例如. form不是第一个选择器.answerContainer.

and this inside an on i the element eg. form not the first selector .answerContainer.

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

    $('.commentContainer').load('../writecomment.php');

    $('.answerContainer').on('submit', 'form', function(event) {
        event.preventDefault();
        var $form = $(this);
        $.ajax({
            "url": $form.attr("action"),
            "data": $form.serialize(),
            "type": $form.attr("method"),
            "response": function() {
                $('.commentContainer').load('../writecomment.php');
                $('.commentBox').val('');
            }
        });
    });
});

这篇关于表单仍在preventDefault上提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆