[英]jQuery submit form without reloading page
我对jQuery不太熟悉。 我正在尝试制作一个在后台提交的表单而不重新加载页面。
我有一个隐藏的div显示和隐藏点击,在div内有一个表单。
我有两个问题:
1)当表单验证失败时,表单仍然会被提交。 我尝试将验证和提交代码置于条件if(validation == valid) { $.ajax.... }
但它无法正常工作。
2)表单提交后,div自动隐藏,因此无法看到成功的消息。
这是代码:
$().ready(function() {
// Validate the form when it is submitted, using validation plugin.
var validator = $("#contactform").validate({
errorContainer: container,
errorLabelContainer: $(),
onkeyup: false,
onclick: false,
onfocusout: false,
errorPlacement: function (error, element) {
error.insertBefore(element);
}
});
});
$(function() {
//This submits a form
$('input[type=submit]').click(function() {
$.ajax({
type: "POST",
url: "contact.php",
data: $("#contactform").serialize(),
beforeSend: function() {
$('#result').html('<img src="loading.gif" />');
},
success: function(data) {
$('#result').html(data);
}
})
})
})
//This shows and hides div onclick
$(document).ready(function(){
$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function(){
$(".slidingDiv").slideToggle();
});
});
您应该绑定到表单的submit
事件,而不是绑定到click事件( input[type=submit]
)。
$("form").on("submit", function (e) {
e.preventDefault();
我也不确定验证。 如果它以异步方式运行,则需要回调。 如果它同步运行,它何时被触发? 似乎应该在提交表单时完成,除非您的验证插件自行完成:
$("form").on("submit", function (e) {
e.preventDefault();
if ($(this).validate(options)) {
$.ajax
使用e.preventDefault
将阻止重新加载,并应允许您的成功div显示。
1)使用event.preventDefault();
保持表单不被提交 - http://api.jquery.com/event.preventDefault/
2)给定脚本中没有任何东西应该导致#result隐藏,但你可以尝试$('#result').show()
并查看是否会将其恢复
请检查您正在使用哪个jQuery版本,因为在jQuery 1.8.2之后,不推荐使用jQuery Ajax的“success”功能。
使用e.preventDefault()
来阻止实际的提交事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.