1

我正在制作一个简单的联系表格,我有一个老式的 php 邮件程序 mail.php 和一个 jQuery 首页,我从那里调用它。

因为我想让它工作,它应该留在同一页面上,但它实际上跳转到 mail.php 并显示消息 Thank you for contacting me. I'll try to reach you ASAP. 虽然它确实发送了邮件,但这仍然是不可接受的,因为这不是我的意图。谁能找出我在这里做错了什么?

任何帮助表示赞赏。

PHP:

<?php   
$name = trim($_POST['name']);

$email = trim($_POST['email']);

if(function_exists('stripslashes')) {
    $message = stripslashes(trim($_POST['message']));
} else {
    $message = trim($_POST['message']);
}

$emailTo = 'myEmail@gmail.com';
$subject = 'Contact Form Submission from '.$name;
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name \n\nEmail: $email \n\nMessage: $message";
$headers = 'From: Saddi website <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

mail($emailTo, $subject, $body, $headers);
echo "Thank you for contacting me. I'll try to reach you ASAP.";
return true;
?>

FORM(那里有很多引导标签,所以为了保持干净,我只是发布):

    <form class="form" action="mail.php" method="post" id="contact-form">


                    </form>

这是我的 AJAX:

    var data_string = jQuery('#contact-form').serialize();

    jQuery.ajax({
        type: "POST",
        url: "mail.php",
        data: {name:name,email:email,message:message}, 
        timeout: 6000,
        error: function(request,error) {
            if (error == "timeout") {
                jQuery('#timedout').fadeIn('slow');
                setTimeout(function() {
                    jQuery('#timedout').fadeOut('slow');
                }, 3000);
            }
            else {
                jQuery('#state').fadeIn('slow');
                jQuery("#state").html('The following error occured: ' + error + '');
                setTimeout(function() {
                    jQuery('#state').fadeOut('slow');
                }, 3000);
            }
        },
        success: function() {
            jQuery('span.valid').remove();
            jQuery('#thanks').fadeIn('slow');
            jQuery('input').val('');
            jQuery('textarea').val('');
            setTimeout(function() {
                jQuery('#thanks').fadeOut('slow');
            }, 3000);
        }
4

1 回答 1

1

首先我会推荐你​​使用 jQuery Form Plugin,它对这种 ajax 发布和验证很有帮助。

jQuery 表单

其次,您可以使用 event.preventDefault(); 避免链接的默认操作,但这实际上取决于您如何将表单触发到 ajax 代码

event.preventDefault

于 2013-11-01T19:40:18.887 回答