我正在使用这个JQuery函数发布表单:
function SubmitForm(form, postaction) {
$(form).submit(function(event){
$('#LoadingDiv').show();
var data = $(this).serialize();
$.post(postaction, data)
.success(function(result){
console.log(result);
$('#LoadingDiv').hide();
$('.tabcontent').html(result);
$("html, body").animate({ scrollTop: 0 }, "slow");
})
.error(function(){
$('.tabcontent').html('Error Loading Page');
$("html, body").animate({ scrollTop: 0 }, "slow");
console.log('Error loading page');
})
return false;
});
}
我在表格上有按钮,如:
<input type="submit" onclick="SubmitForm('#SearchHistoricInvoices', '/billing/viewhistoricinvoices.php');" value="Search" />
和表单标记:
<form method="post" id="SearchHistoricInvoices">
但是当使用上面的按钮提交表单时,它似乎只是刷新整个页面而不是实际提交表单
我已经检查了控制台,并且没有错误
答案 0 :(得分:2)
您应该直接使用该函数,而不是在另一个函数内调用。
$('#SearchHistoricInvoices').submit(function(event){
event.preventDefault()
$('#LoadingDiv').show();
var data = $(this).serialize();
$.post($(this).prop('action'), data)
.success(function(result){
console.log(result);
$('#LoadingDiv').hide();
$('.tabcontent').html(result);
$("html, body").animate({ scrollTop: 0 }, "slow");
})
.error(function(){
$('.tabcontent').html('Error Loading Page');
$("html, body").animate({ scrollTop: 0 }, "slow");
console.log('Error loading page');
})
return false;
});
尝试在第一行使用jQuery event.preventDefault()
,如上所述here。
您的代码应该是这样的
function SubmitForm(form, postaction) {
$(form).submit(function(event){
event.preventDefault()
$('#LoadingDiv').show();
var data = $(this).serialize();
$.post(postaction, data)
.success(function(result){
console.log(result);
$('#LoadingDiv').hide();
$('.tabcontent').html(result);
$("html, body").animate({ scrollTop: 0 }, "slow");
})
.error(function(){
$('.tabcontent').html('Error Loading Page');
$("html, body").animate({ scrollTop: 0 }, "slow");
console.log('Error loading page');
})
return false;
});
}
这将停止默认submit event
,并将使用jQuery post发送请求。
答案 1 :(得分:0)
问题是因为在表单提交后,您只附加了表单submit
处理程序。改变你的逻辑以使用jQuery事件挂钩,它变得更简单和整洁。试试这个:
<form method="post" id="SearchHistoricInvoices" action="/billing/viewhistoricinvoices.php">
<!-- other inputs -->
<input type="submit" value="Search" />
</form>
$('#SearchHistoricInvoices').submit(function(event) {
event.preventDefault();
$('#LoadingDiv').show();
$.post($(this).prop('action'), $(this).serialize()).success(function(result){
console.log(result);
$('#LoadingDiv').hide();
$('.tabcontent').html(result);
$("html, body").animate({ scrollTop: 0 }, "slow");
}).error(function(){
$('.tabcontent').html('Error Loading Page');
$("html, body").animate({ scrollTop: 0 }, "slow");
console.log('Error loading page');
})
});