简体   繁体   English

表单不会使用Ajax提交,但通常会

[英]Form wont submit with ajax, but will normally

Consider the following code: 考虑以下代码:

$('.saveCheck').on('click',function()
   {
        var frm = $(this).parents('form');
        frm.submit(function (ev)
        {   
            $.ajax
                ({
                    type: frm.attr('method'),
                    url: frm.attr('action'),
                    data: frm.serialize(),
                    success: function (data)
                    {alert("hooray!");}
            });
            ev.preventDefault();
        });  
   });

This will not submit my form, however: 但是,这不会提交我的表格:

frm.submit();

On its own works fine, but wont have any of the AJAX goodness. 就其本身而言,可以很好地工作,但是不会具有任何AJAX优点。

Is there any glaringly obvious reason for this? 有什么明显的原因吗?

You code is set up so that when saveCheck is clicked it will bind a submit handler so that when the form is later submitted, it will call the Ajax function. 设置您的代码,以便在单击saveCheck时将绑定一个提交处理程序,以便以后提交表单时将调用Ajax函数。

It sounds like what you want to do is to just run the Ajax function when saveCheck is clicked. 听起来您想要做的就是单击saveCheck时仅运行Ajax函数。 Get rid of your submit handler binding entirely. 完全摆脱您的提交处理程序绑定。

$('.saveCheck').on('click', function(ev) {
    var frm = $(this).parents('form');
    $.ajax({
        type: frm.attr('method'),
        url: frm.attr('action'),
        data: frm.serialize(),
        success: function(data) {
            alert("hooray!");
        }
    });
    ev.preventDefault();
});

That said, you should probably be using a submit handler on the form instead of a click handler on a button. 也就是说,您可能应该在表单上使用提交处理程序,而不是在按钮上使用单击处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM