使用Jquery和AJAX进行表单validation

我正在使用AJAX和JQUERY来调用PHP脚本来validation用户电子邮件。 但是,由于某种原因,表格即使不应该提交。 我究竟做错了什么? 我知道错误肯定不在我的PHP中。

我的代码:

$("#signup").submit(function() { var error= false; var dataString = $(this).serialize(); var email= $("#email").val().trim(); if (email != 0) { // Run AJAX email validation and check to see if the email is already taken $.ajax({ type: "POST", url: "checkemail.php", data: dataString, async: false, success: function(data) { var error= false; if (data == 'invalid') { var invalid= 1; } else if (data == 'taken') { var taken= 1; } if (invalid == 1) { alert('invalid email'); error = true; } if (taken == 1) { alert('email taken'); error = true; } if (error == true) { return false; } } }); } }); 

尝试更新这些:

 $("#signup").submit(function(e) { //<----pass the event here as "e" e.preventDefault(); //<----stops the form submission var error= false; var dataString = $(this).serialize(); var email= $.trim($("#email").val()); //<----use trim this way 

如果您绝对必须使用AJAX进行表单提交,这可能是更好的方法:

 $('form').submit({ $.ajax({ type:'post', url: 'someurl.php', data: dataString, context: this, // this here refers to the form object success:function(data) { // perform your operations here if(something_is_wrong) { // show message to user } else { this.submit(); // put this code in the block where all is ok } } }); return false; // makes sure the form doesn't submit });