Form still submits on preventDefault

穿精又带淫゛_ 提交于 2019-12-20 05:28:10

问题


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:

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

回答1:


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??

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

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('');
            }
        });
    });
});


来源:https://stackoverflow.com/questions/8690117/form-still-submits-on-preventdefault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!