我正在网站上工作。
问题: 当我点击"提交"我希望成功或错误消息改变类并出现在我的表单下。但是,"提交"按钮添加"?"到我的网址,因此,我的页面刷新,所有元素加载默认类。
问题:如何阻止我提交"提交"添加"?"的按钮到我的网址?或者我做错了吗?
代码如下所示:
在我的.js文件中提交函数:
$(".form-horizontal").submit(function (e) {
e.preventDefault();
var fname = $("#first-name").val();
var lname = $("#last-name").val();
var email = $("#email").val();
var subject = $("#subject").val();
var message = $("#message").val();
var dataString = 'fname=' + fname + 'lname=' + lname + '&email=' + email + '&subject=' + subject + '&message=' + message;
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
if (isValidEmail(email) && (message.length > 1) && (fname.length > 1)) {
$.ajax({
type: "POST",
url: "sendmail.php",
data: dataString,
success: function () {
$('.contact-success').fadeIn(1000);
$('.contact-error').fadeOut(500);
}
});
} else {
$('.contact-error').fadeIn(1000);
$('.contact-success').fadeOut(500);
}
return false;
});

php文件:
<?php
// Email Submit
// Note: filter_var() requires PHP >= 5.2.0
if ( isset($_POST['email']) && isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['subject']) && isset($_POST['message']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
// detect & prevent header injections
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if ( preg_match( $test, $val ) ) {
exit;
}
}
//
mail( "email@domain.com", $_POST['subject'], $_POST['message'], "From:" . $_POST['email'] );
}
?>
更新 非常感谢您在评论中提出建议!
Errors that I get on submit. I also get them on some of my pages.
$(document).ready(function()
包裹。<form class="form-horizontal" role="form">
课程。如果我无法弄清楚,我想我会创建单独的&#34;感谢您提交信息&#34;页。有点解决方法))
代码运行时元素是否存在? - 需要多考虑一下!我会检查一下!