在执行action属性之前,我需要验证HTML表单。但这让我很难过。请参阅其他声明中的评论,以及返回false后的评论,以解释此问题
$(document).ready(function(){
$("#ajax-payment-form").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
success: function(msg) {
// Message Sent - Show the 'Thank You' message and hide the form
if(msg == 'OK') {
alert("success");
} else {
event.preventDefault(); // I have tried with or without this method
alert("fail");
}
}
});
return false; // when return false, the action will not execute. If false is removed the action will execute, even if event.precentDefault(); is called in the else statement.**
});
});
感谢您抽出时间,
Troels
return false;
将始终在ajax函数的结果返回给您之前激发。考虑到您当前的情况,最简单的方法是从success函数中调用this.submit()
,但在默认情况下始终调用return false;
。这将避免递归,而且异步调用也不再有问题。
$(document).ready(function(){
$("#ajax-payment-form").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this, //needed to tell the ajax function that "this" belongs to the form, not the ajax call.
success: function(msg) {
// Message Sent - Show the 'Thank You' message and hide the form
if(msg == 'OK') {
alert("success");
this.submit(); //it's magic, john.
} else {
//no reason to prevent the default, as the form will automatically return false anyway.
alert("fail");
}
}
});
return false; //just leave this right here.
});
});
问题有两个方面:函数调用中没有声明event
,成功函数时没有提交表单。提交事件的逻辑应该如下:
- 收听
<form>
元素上的submit
事件 - 使用
e.preventDefault()
首先阻止默认表单操作 - 进行AJAX调用。根据返回数据的结果,决定是否继续提交表单。我强烈建议不要使用不推荐使用的
jqXHR.success
函数,而是使用延迟的jqXHR.done()
或jqXHR.fail()
函数
此外,您可以始终使用console.log()
检查脚本,而不是依赖于阻止下游代码执行的alert()
。这是代码:
$(function(){
$("#ajax-payment-form input[type='submit']").click(function(e) {
// Prevent form submission
e.preventDefault();
// Serialize data, make AJAX call
var str = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this // So that you can use $(this) later
}).done(function(msg) {
// If a response is received from your server
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$(this).closest('form').submit();
} else {
console.log('Validation failed, will not do anything more');
}
}).fail(function() {
// Catch ajax errors here
console.log('AJAX error');
});
});
});