通过AJAX jQuery中提交表单表单、AJAX、jQuery

2023-09-11 00:34:09 作者:笑很甜

我使用下面的jQuery的code通过AJAX提交表单。

I using following jQuery code to submit a form via AJAX.

jQuery('form.AjaxForm').submit( function() {            
        $.ajax({
            url     : $(this).attr('action'),
            type    : $(this).attr('method'),
            dataType: 'json',
            data    : $(this).serialize(),
            success : function( data ) {
                        alert('Submitted')
                      },
            error   : function( xhr, err ) {
                        alert(''Error);     
                      }
        });    
        return false;
    });

以上code为正常使用时的形式装入整个页面。如果我通过AJAX加载的形式但是这个jQuery不起作用。我想这是因为通过JavaScript加载后阿贾克斯加载方式。

任何解决方案??

感谢

推荐答案

如果使用jQuery 1.7+,你可以尝试使用。对()委派的事件,并绑定到所有未来的形式与同一类。 尝试寻找未插入的$(document)动态地而不是最近的父。

If using jQuery 1.7+ you could try using .on() to delegate the event and bind to all future forms with the same class. Try finding the closest parent that is not inserted dynamicly instead of $(document).

$(document).on('submit', 'form.AjaxForm', function() {            
        $.ajax({
            url     : $(this).attr('action'),
            type    : $(this).attr('method'),
            dataType: 'json',
            data    : $(this).serialize(),
            success : function( data ) {
                         alert('Submitted');
            },
            error   : function( xhr, err ) {
                         alert('Error');     
            }
        });    
        return false;
    });