我試圖讓一個Ajax功能,可以讓我的網站發送信息給我無需刷新頁面。但不知何故,我不能這樣做,因爲每次我點擊它,我在控制檯收到此錯誤:阿賈克斯的錯誤:無法加載資源:服務器迴應500(內部服務器錯誤)的狀態
無法加載資源:服務器500(內部服務器錯誤)的狀態迴應。
這裏是我的腳本:
$(function() {
var form = $('#ajax-contact');
var formMessages = $('#form-messages');
$(form).submit(function(event) {
event.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
}).done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
}).fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
這是我的PHP文件:
<?php
// 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 (empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "All fields must be filled.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "[email protected]";
// Set the email subject.
$subject = "New Message from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\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 "Something went wrong.";
}
} 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.";
}
?>
檢查網址是否正確,如果是,那麼它可能是在你的服務器端 –
一個問題的URL是正確的。那麼我該怎麼處理這個問題呢,我對此很新,對不起。 @NishithChaturvedi – Angelica
告訴我們你得到的內部服務器錯誤沒有多大幫助。查看服務器錯誤日誌並告訴我們錯誤實際上是什麼! – Quentin