我想使用带有ajax调用和PHP的Jquery构建一个简单的联系表单。但它不起作用,我看不出为什么。您可以认为 id 或类名没有错误。
我的爪哒语
jQuery('#contacter').click(function () {
var postdata = $('.contact-form form').serialize();
$.ajax({
type: 'POST',
url: 'contact.php',
data: postdata,
success: function () {
$('.contact-form form').fadeOut('fast', function () {
$('.contact-form').append('<p>Thanks for contacting us! We will get back to you very soon.</p>');
});
}
});
});
我的菲律宾比索
<?php
// Enter the email where you want to receive the message
$emailTo = 'example@gmail.com';
$clientEmail = addslashes(trim($_POST['email']));
$subject = addslashes(trim($_POST['subject']));
$message = addslashes(trim($_POST['message']));
$antispam = addslashes(trim($_POST['antispam']));
$headers = "From: " . $clientEmail . " <" . $clientEmail . ">" . "'r'n" . "Reply-To: " . $clientEmail;
mail($emailTo, $subject , $message, $headers);
?>
我的网站刷新时未发送邮件。我已经用一个简单的mail()测试了我的服务器,它工作正常:服务器端没有问题。
在我看来
,问题是提交表单时会发生回发。当您在按钮上使用click
事件(假设)时,其默认行为是提交表单,这会导致回发。
由于您使用 ajax 将值提交到后端,因此您需要使用 event.preventDefault()
来停止表单提交/默认行为。
您必须通过以下方式停止事件event.preventDefault()
:
jQuery('#contacter').click(function (e) { // <-----pass e for event here
e.preventDefault(); // and stop it here
如果您正在使用form
元素,那么最好使用submit
事件:
jQuery('.contact-form form').submit(function(e) { // e in the args
e.preventDefault(); // stop the submission here.
var postdata = $(this).serialize();
$.ajax({
type: 'POST',
url: 'contact.php',
data: postdata,
success: function() {
$('.contact-form form').fadeOut('fast', function() {
$('.contact-form').append('<p>Thanks for contacting us! We will get back to you very soon.</p>');
});
}
});
});