我在表单上设置了一个ajax调用,将post事件发送到我的php邮件程序脚本。但是,帖子转到url / undefined而不是mailer.php,错误'在此服务器上找不到请求的URL / undefined。'返回代码404。这是ajax脚本:
$("#contactForm").on("submit", function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "Did you fill in the form properly?");
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
function submitForm(){
// Initiate Variables With Form Content
var email = $("#email").val();
$.ajax({
type: "POST",
url: "mailer.php",
data: "email=" + email,
complete : function(text){
if (text == "success"){
console.log(text);
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
}
function formSuccess(){
$("#contactForm")[0].reset();
submitMSG(true, "Awesome! We'll be in touch.")
}
function formError(){
$("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
$(this).removeClass();
});
}
我已将PHP脚本放在同一个文件夹中,但似乎找不到php脚本时出错。
<?php
// My modifications to mailer script from:
// http://blog.teamtreehouse.com/create-ajax-contact-form
// Added input sanitizing to prevent injection
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "test@test.com";
// Set the email subject.
$subject = "Hello";
// Build the email content.
$email_content .= "hello";
// Build the email headers.
$email_headers = "From: $name <test@test.com>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
// http_response_code(200);
echo "success";
} 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.";
}
?>
我还有一个.htaccess文件:
RewriteEngine On RewriteBase /
# redirect html pages to the root domain
RewriteRule ^index\.html$ / [NC,R,L]
# remove trailing html on routes
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html