【问题标题】:Ajax Form Post and Validation Not WorkingAjax 表单发布和验证不起作用
【发布时间】:2015-10-12 10:11:44
【问题描述】:

我尝试使用 Ajax 和 jquery 表单验证来发布数据,但它在第一次提交功能和验证时不起作用。有什么解决办法吗?

$(document).ready(function() {
$("#myForm").validate();
});

(function($){
    function processForm( e ){
        $.ajax({
            url: 'post.php',
            dataType: 'text',
            type: 'post',
            contentType: 'application/x-www-form-urlencoded',
            data: $(this).serialize(),
            success: function( data, textStatus, jQxhr ){
                //$('#response pre').html( data );
                alert('scuss');
            },
            error: function( jqXhr, textStatus, errorThrown ){
                //console.log( errorThrown );
                alert('error');
            }
        });

            e.preventDefault();
    }

$('#myForm').submit(function(e){
e.preventDefault();
if(!$("#myForm").valid()) return; 
$('#myForm').submit( processForm ); 
}); 
})(jQuery);

【问题讨论】:

    标签: jquery ajax forms validation


    【解决方案1】:

    你为什么在submit 中调用submit?只需在else 部分中调用function processForm,如下所示:

    $('#myForm').submit(function(e){
        e.preventDefault();
        if(!$(this).valid()) 
           return; 
        else
           processForm($(this));
    }); 
    

    无需传递e 来运行,因为您已经阻止了form 的默认action,而是传递form 本身。

    function processForm(form){
         var $this=$(form);//cache the form
         $.ajax({
               url: 'post.php',
               dataType: 'text',
               type: 'post',
               contentType: 'application/x-www-form-urlencoded',
               data: $this.serialize(),
               success: function( data, textStatus, jQxhr ){
                    //$('#response pre').html( data );
                    alert('scuss');
               },
               error: function( jqXhr, textStatus, errorThrown ){
                    //console.log( errorThrown );
                    alert('error');
               }
          });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多