[英]Ajax prevent default and submit form on current page
我有以下脚本,它完美地工作但是问题是我需要一个form action attribute
才能工作,因此我的问题是如何修改我当前的脚本以防止默认表单提交行为并在当前页面上提交表单而不需要表单中的action attribute
$(function() {
var form = $('#editRes');
var formMessages = $('#formMsg');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
//do the validation here
if (!validateLog()) {
return;
}
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
}).done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error').addClass('success');
// Set the message text.
$(formMessages).html(response); // < html();
// Clear the form.
$('').val('')
}).fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success').addClass('error');
// Set the message text.
var messageHtml = data.responseText !== '' ? data.responseText : 'Oops! An error occured!.';
$(formMessages).html(messageHtml); // < html()
});
});
function validateLog() {
var valid = true;
//VALIDATE HERE
return valid;
}
})
在你的ajax中,你使用的是url: $(form).attr('action')
。 这意味着表单将被提交给表单的action
属性。 由于没有,ajax将无法工作。
如果您希望表单没有action
标记,您可以在ajax url部分中编写表单submit url( page.php )
$.ajax({
type: 'POST',
url: 'page.php',
data: formData,
...
...
});
另一个选择是window.location.href
。
附注:您不需要在$()
重新换行form
,因为它已经是第二行中的jQuery对象 - 对于formMessages
。
$(function() {
var form = $('#editRes'); // this is a jQuery object
var formMessages = $('#formMsg'); // this is also a jQuery object
// Set up an event listener for the contact form.
form.submit(function (e) {
// Stop the browser from submitting the form.
e.preventDefault();
// do the validation here
if (!validateLog()) {
return;
}
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: window.location.href,
data: form.serialize()
}).done(function(response) {
// Make sure that the formMessages div has the 'success' class.
formMessages.removeClass('error').addClass('success');
// Set the message text.
formMessages.html(response); // < html();
// Clear the form.
$('').val('')
}).fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
formMessages.removeClass('success').addClass('error');
// Set the message text.
var messageHtml = data.responseText !== '' ? data.responseText : 'Oops! An error occured!.';
formMessages.html(messageHtml); // < html()
});
});
function validateLog() {
var valid = true;
//VALIDATE HERE
return valid;
}
});
在提交功能结束时添加:
return false;
这将阻止浏览器导航。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.