我将这样做。我简化了代码以便更好地理解。
选项 1:一个文件 (contact.php)、一个表单、无 ajax、无 onclick 事件:
<?php
$emailSent = FALSE;
/*
* ===================================
* Run operations upon form submission
* ===================================
*/
if (isset($_POST['submit'])) {
/*
* ==========================
* Validate the posted values
* ==========================
*/
if (!isset($_POST['name']) || empty($_POST['name'])) {
$errors[] = 'Please provide a name.';
}
if (!isset($_POST['email']) || empty($_POST['email'])) {
$errors[] = 'Please provide an email.';
} elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Invalid email.';
}
/*
* ======================================
* Send the email if all values are valid
* ======================================
*/
if (!isset($errors)) {
$name = $_POST['name'];
$email = $_POST['email'];
// Send the email here, using the posted values...
$emailSent = TRUE;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="messages">
<?php
if (isset($errors)) {
foreach ($errors as $error) {
?>
<div class="error">
<?php echo $error; ?>
</div>
<?php
}
} elseif ($emailSent) {
?>
<div class="success">
The email was successfully sent.
</div>
<?php
}
?>
</div>
<form action="" method="POST">
<input type="text" id="mail-name" name="name" />
<input type="email" id="mail-email" name="email" />
<button class="mail-submit" id="mail-submit" type="submit" name="submit">
Send e-mail
</button>
</form>
</body>
</html>
选项 2:两个文件,一个 ajax,一个 onclick 事件,根本没有表单:
联系.php:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function (event) {
$.ajax({
method: 'post',
dataType: 'html',
url: 'send-email.php',
data: {
'name': $('#name').val(),
'email': $('#email').val()
},
success: function (response, textStatus, jqXHR) {
$('.messages').html(response);
},
error: function (jqXHR, textStatus, errorThrown) {
var message = 'An error occurred during your request. Please try again, or contact us.';
$('.messages').html('<div class="error">' + message + '</error>');
}
});
});
});
</script>
</head>
<body>
<div class="messages"></div>
<div class="contact-form">
<input type="text" id="name" name="name" />
<input type="email" id="email" name="email" />
<button type="button" id="submit" name="submit">
Send e-mail
</button>
</div>
</body>
</html>
发送电子邮件.php:
<?php
$response = '';
$emailSent = FALSE;
/*
* ==========================
* Validate the posted values
* ==========================
*/
if (!isset($_POST['name']) || empty($_POST['name'])) {
$errors[] = 'Please provide a name.';
}
if (!isset($_POST['email']) || empty($_POST['email'])) {
$errors[] = 'Please provide an email.';
} elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Invalid email.';
}
/*
* ======================================
* Send the email if all values are valid
* ======================================
*/
if (!isset($errors)) {
$name = $_POST['name'];
$email = $_POST['email'];
// Send the email here, using the posted values...
$emailSent = TRUE;
}
/*
* ==============================================================
* Assign the corresponding message (with error or success class)
* ==============================================================
*/
if (isset($errors)) {
foreach ($errors as $error) {
$response .= '<div class="error">' . $error . '</div>';
}
} elseif ($emailSent) {
$response .= '<div class="success">The email was successfully sent.</div>';
}
/*
* ==================
* Print the response
* ==================
*/
echo $response;
可选:选项 1 也带有客户端验证:
您可以在提交之前验证表单,如果至少一个字段无效(空值、虚假电子邮件地址等),您可以停止提交并显示相应的错误消息:
<?php
$emailSent = FALSE;
/*
* ===================================
* Run operations upon form submission
* ===================================
*/
if (isset($_POST['submit'])) {
/*
* ==========================
* Validate the posted values
* ==========================
*/
if (!isset($_POST['name']) || empty($_POST['name'])) {
$errors[] = 'Please provide a name.';
}
if (!isset($_POST['email']) || empty($_POST['email'])) {
$errors[] = 'Please provide an email.';
} elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Invalid email.';
}
/*
* ======================================
* Send the email if all values are valid
* ======================================
*/
if (!isset($errors)) {
$name = $_POST['name'];
$email = $_POST['email'];
// Send the email here, using the posted values...
$emailSent = TRUE;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// The form will not submit before all fields are valid.
$('.contact-form').submit(function (event) {
var messages = [];
var name = $.trim($('#name').val());
var email = $.trim($('#email').val());
// Validate user input.
if (name === '') {
messages.push('Please provide a name.');
}
if (email === '') {
messages.push('Please provide an email.');
}
// Display the error messages, if any.
if (messages.length > 0) {
$('.messages').html('');
for (var i = 0; i < messages.length; i++) {
$('.messages').append('<div class="error">' + messages[i] + '</div>');
}
// Abort the form submission.
return false;
}
// Continue the form submission.
return true;
});
});
</script>
</head>
<body>
<div class="messages">
<?php
if (isset($errors)) {
foreach ($errors as $error) {
?>
<div class="error">
<?php echo $error; ?>
</div>
<?php
}
} elseif ($emailSent) {
?>
<div class="success">
The email was successfully sent.
</div>
<?php
}
?>
</div>
<form class="contact-form" action="" method="POST">
<input type="text" id="mail-name" name="name" />
<input type="email" id="mail-email" name="email" />
<button class="mail-submit" id="mail-submit" type="submit" name="submit">
Send e-mail
</button>
</form>
</body>
</html>
当然,对于选项 2,您可以轻松实现这样的验证,方法是将验证代码包含在 onclick 处理程序中,并且如果输入无效则不运行 ajax 请求。
祝你好运!