我正在努力使用JavaScript脚本,该脚本应验证并使用Ajax提交表单。 一切工作正常,但由于某种原因,ajax部分无法正常工作。单击提交后,似乎一切正常,但是在最后一秒,它将我重定向到具有成功消息的.php文件。
有些难以解释。表单已正确发送,但没有按预期保留在form.html页面上。
我离使用JavaScript的专业人士还很远。你们可以看看我的剧本,然后告诉我我做错了什么吗?
$(function () {
'use strict';
window.addEventListener('load', function () {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
if (form.checkValidity() === true) {
$.ajax({
type: "POST",
url: "email/personal-contact.php",
data: $(this).serialize(),
success: function (data)
{
// type of the message: success / danger + message
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>' + messageText + '</div>';
if (messageAlert && messageText) {
// inject the alert to .messages div
$('#returnmessage').html(alertBox);
// empty the form
$('#personalcontactform')[0].reset();
$('#personalcontactform').removeClass('was-validated');
}
}
});
}
}, false);
});
}, false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
非常感谢。
修改:
感谢Chris G的评论。实际上,在event.preventDefault();
之后添加if (form.checkValidity() === true) {
就是这样。