在event.preventDefault之后提交表单?

时间:2015-07-13 16:56:53

标签: javascript jquery ajax post

我知道这个问题已被问过一百万次,但我似乎无法让它发挥作用。有人能让我知道我做错了什么。

这是我的代码:

$('#frm').submit(function(event) {
    event.preventDefault();
    var formData = $(this).serialize();
    var email = $('input#email').val();
    if (email == '') {
        alert('Please enter your email address');
        $('input#email').focus();
        return false;
    } else {
        $.post('http://www.domain.com/', formData, function() {
            $('#frm').submit();
        });
    }
});

3 个答案:

答案 0 :(得分:1)

您可以使用DOM节点提交方法提交FORM:

$.post('http://www.domain.com/', formData, function() {
    this.submit(); // 'this' not '$(this)'
}.bind(this)); // 'bind' to set relevant context, or use jq $.proxy(handler, this) to support older browsers

答案 1 :(得分:0)

此代码没有意义

    $.post('http://www.domain.com/', formData, function() {
        $(this).submit();
    });

您正在发帖,然后,当请求成功返回时,您是否尝试再次在表单上调用提交?

顺便说一句,该上下文中的this引用了Ajax调用的jqXHR对象而不是表单。见$(this) inside of AJAX success not working

答案 2 :(得分:0)

正如大多数答案所说,this不是对表格的引用。然后,您需要为它创建一个引用,如下所示(请参阅that var)。只有在以后想要在success回调中使用它时才需要HOwever:

$('#frm').submit(function(event) {

    // Create a reference to your form
    var that = this;

    event.preventDefault();
    var formData = $(this).serialize();
    var email = $('input#email').val();
    if (email == '') {
        alert('Please enter your email address');
        $('input#email').focus();
        return false;
    } else {
        $.post('http://www.domain.com/', formData, function() {

            // On success response do your stuff here and 
            // submit to your 'own domain'  
            // In case you don't have the action attr, give a value to this var.
            var url = $(that).attr('action'); 
            $.post(url, formData, function() {
                // On success response do your stuff here
            });
        });
    }
});