表单提交在第一次单击时不起作用

时间:2014-04-01 15:46:14

标签: jquery ajax jquery-forms-plugin

我遇到了'事件冒泡'的问题所以我正在使用'.on'事件来阻止这种情况,但现在当我尝试提交表单时,它将无法工作,直到您单击提交按钮两次。即第一次点击没有任何反应。

我尝试过在网上找到的所有内容。

有没有人有任何想法如何解决这个问题?

$(document).on('submit', '.status_update_shipped', function(e) {
    $('.status_update_shipped').ajaxForm({
        dataType: 'json',
        success: function(data) {
            if (data.success) {
                $('#order-alert').text('Order #'+data.entry_id+' set as shipped (moved to past orders)').fadeIn();
                setTimeout(function(){
                    $('#order-alert').fadeOut().text('');
                }, 5000);
                var wrapper = '.recent-order-item-'+data.entry_id;
                $(wrapper).hide();
            }
        }
    });
    e.preventDefault();
});

2 个答案:

答案 0 :(得分:3)

调用.ajaxForm()只是初始化 the Forms plugin,而不是实际提交。你不需要将它包装在事件处理程序中,因为插件会自动处理所有事情...捕获点击,阻止默认提交,以及执行ajax ...否则,没有指出使用插件。

(您需要点击两次,因为第一次点击只是初始化插件。)

按照文档中的示例进行操作:http://malsup.com/jquery/form/

$(document).ready(function() {

    $('.status_update_shipped').ajaxForm({ 
        // your options
    });

});

另外,在您加入jQuery之后,不要忘记包含Forms插件。

<script src="http://malsup.github.com/jquery.form.js"></script>

答案 1 :(得分:0)

这个答案是使用&#34; ajaxSubmit&#34;而不是&#34; ajaxForm&#34;

http://malsup.com/jquery/form/#options-object

$(document).on('submit', '.status_update_shipped', function(e) {
    $('.status_update_shipped').ajaxSubmit({
        dataType: 'json',
        success: function(data) {
            if (data.success) {
                $('#order-alert').text('Order #'+data.entry_id+' set as shipped (moved to past orders)').fadeIn();
                setTimeout(function(){
                    $('#order-alert').fadeOut().text('');
                }, 5000);
                var wrapper = '.recent-order-item-'+data.entry_id;
                $(wrapper).hide();
            }
        }
    });

    e.preventDefault();
    return false;
});
相关问题