【发布时间】:2014-10-08 12:44:34
【问题描述】:
在以下代码中,我有一个联系表单,并且在该表单中有一个电子邮件验证脚本。作为验证的结果,我希望错误消息显示在名为确认的div 中,而无需重新加载页面。此外,如果电子邮件有效,邮件将被发送,我希望感谢消息显示在相同的div 确认中。问题是如何防止重新加载页面并让错误消息或感谢消息显示在确认 div 中?
<html>
<body>
<?php
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return TRUE;
} else {
return FALSE;
}
}
?>
<?php
if (!isset($_POST["submit"])) {
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
From: <input type="text" name="from"><br>
Subject: <input type="text" name="subject"><br>
Message: <textarea rows="10" cols="40" name="message"></textarea><br>
<input type="submit" name="submit" value="Submit Feedback"><br>
<div id="confirmation" style="display:none" align="center"></div>
</form>
<?php
} else { // the user has submitted the form
// Check if the "from" input field is filled out
if (isset($_POST["from"])) {
// Check if "from" email address is valid
$mailcheck = spamcheck($_POST["from"]);
if ($mailcheck==FALSE) {
echo"
<script>
document.getElementById('confirmation').text ='invalid email';
</script>";
} else {
$from = $_POST["from"]; // sender
$subject = $_POST["subject"];
$message = $_POST["message"];
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
mail("nawe11@gmail.com",$subject,$message,"From: $from\n");
echo"
<script>
document.getElementById('confirmation').text ='Thank you';
</script>";
}
}
}
?>
</body>
</html>
谢谢
【问题讨论】:
-
你可以使用 Ajax 做你想做的事
-
您需要使用 AJAX 提交表单,然后您将获得响应并显示适当的绝对定位 div(错误消息,感谢消息)
-
document.getElementById('confirmation').innerHTML = '<div>test</div>';
标签: javascript php html email