创建一个简单的电子邮件提交表单,并希望使用AJAX。老实说,我有点卡住了。经过几个小时的研究,这是我到目前为止的工作,我希望这里的人可以帮助我完成实际的AJAX提交电话。
HTML表单
<!-- Signup Form -->
<form id="signup-form" method="post" action="mailer.php">
<input type="email" name="email" id="email" placeholder="Email Address" />
<input type="submit" value="Sign Up" />
</form>
<script src="assets/js/main.js"></script>
main.js
// Signup Form.
(function() {
// Vars.
var $form = document.querySelectorAll('#signup-form')[0],
$submit = document.querySelectorAll('#signup-form input[type="submit"]')[0],
$message;
// Bail if addEventListener isn't supported.
if (!('addEventListener' in $form))
return;
// Message.
$message = document.createElement('span');
$message.classList.add('message');
$form.appendChild($message);
$message._show = function(type, text) {
$message.innerHTML = text;
$message.classList.add(type);
$message.classList.add('visible');
window.setTimeout(function() {
$message._hide();
}, 3000);
};
$message._hide = function() {
$message.classList.remove('visible');
};
// Events.
// Note: If you're *not* using AJAX, get rid of this event listener.
$form.addEventListener('submit', function(event) {
event.stopPropagation();
event.preventDefault();
// Hide message.
$message._hide();
// Disable submit.
$submit.disabled = true;
// Process form.
// Note: Doesn't actually do anything yet (other than report back with a "thank you"),
// but there's enough here to piece together a working AJAX submission call that does.
window.setTimeout(function() {
// Reset form.
$form.reset();
// Enable submit.
$submit.disabled = false;
// Show message.
$message._show('success', 'Thank you!');
//$message._show('failure', 'Something went wrong. Please try again.');
}, 750);
});
})();
mailer.php
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
// Set the recipient email address.
$recipient = “mike@aol.com”;
// Set the email subject.
$subject = "New contact from $email";
// Build the email content.
$email_content .= "Email: $email\n\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
我们将不胜感激任何帮助或指向正确方向的点