jQuery - Resume form submit after ajax call

前端 未结 3 1608
萌比男神i
萌比男神i 2020-12-05 22:02

Is it possible to stop a form from submitting and then resubmitting the same form from within the success of an ajax call?

At the moment it gets to the success bit b

3条回答
  •  -上瘾入骨i
    2020-12-05 22:39

    It's no good practice to reselect all form tags throughout your code, what if you have multiple forms on the page? Also you'd better use .on() and .off() with jQuery.

    $(document).ready(function() {
        $('form').on('submit', function(e) {
            e.preventDefault();
    
            // cache the current form so you make sure to only have data from this one
            var form = this,
                $form = $(form);
    
            $.ajax({
                url: form.action,
                type: form.method,
                data: $form.serialize(),
                success: function(data) {
                    if (data == 'true')
                    {
                        $form.attr('action', 'http://example.com').off('submit').submit();
                    }
                    else
                    {
                        alert('Your username/password are incorrect');
                    }
                },
                error: function() {
                    alert('There has been an error, please alert us immediately');
                }
            });
        });
    });
    

提交回复
热议问题