ajax 提交 bootstrap 联系表单时 $_POST 变量为空

$_POST variable is empty on ajax submission of a bootstrap contact form

我知道以前有人问过这样的问题,但其中 none 帮助我解决了这个问题。如果这是我忽略的愚蠢的事情,那么我提前道歉。我已经在 bootstrap 模态中设置了联系表格。表格的 html 如下:

<div class="modal-body">
    <form id="contactForm" action="contact.php" method="post">
        <div class='form-group'>
            <label class='sr-only' for="name" sr-only="Name">Name</label>
            <input id="name" type="text" name="name" class="form-control" placeholder="Name">
        </div>
        <div class='form-group'>
            <label class='sr-only' for="email" sr-only="Email address">Email</label>
            <input id="email" type="email" name="email" class="form-control" placeholder="Email address">
        </div>
        <div class='form-group'>
            <label class='sr-only' for="message" sr-only="Your Message"></label>
            <textarea id="message" type="text" name="message" rows='6' class="form-control" placeholder='Type your message here...'></textarea>
        </div>
        <br>
        <div class="form-group">
            <label class="control-label" for="human" sr-only="Prove you're human.  What is 3 + 2?">Prove you're human:  3 + 2 = ?</label>
            <input type="text" class="form-control" id="human" name="human" placeholder="Type the number here">
        </div>
        <br>
        <button id='contactFormSubmit' type='submit' name='submit' class='form-control btn btn-block btn-lg btn-info'>
            <i class='fa fa-send'></i>&nbsp;&nbsp;Send Message
        </button>
    </form>
</div>

下面是 ajax 请求。请注意,有一些表单验证; ajax 大约是代码的一半:

$('form#contactForm').submit(function(e) {
    e.preventDefault();
    $('input.borderRed, textarea.borderRed').removeClass('borderRed');
    var name = $('#name');
    var email = $('#email');
    var message = $('#message');
    var human = $('#human');
    var vals = [name, email, message, human];
    var emptyVals = [];
    for(var i=0; i < vals.length; i++) {
        if (vals[i].val() == '') {
            vals[i].addClass('borderRed');
            emptyVals.push(vals[i]);
        }
    }
    if (emptyVals.length > 0) {
        $('#intro').append('<div class="alert alert-danger alert-dismissable fade show"><strong>Please fill in all fields to send a message.</strong><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>');
        return false;
    } else if(human.val() != 5) {
        $('#intro').append('<div class="alert alert-danger alert-dismissible fade show"> <strong>Try that math problem again!</strong><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>');
        human.addClass('borderRed');
        return false;
    } else {
        $.ajax({
            data: $(this).serialize(),
            type: "POST",
            url: "contact.php", 
            success:function(response) {
                if (response == 'success') {
                    $('#intro').append('<div class="alert alert-success alert-dismissible fade show"> <strong>Your message was sent successfully.</strong><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>');
                    $('.borderRed').removeClass('borderRed');
                } else {
                    $('#intro').append('<div class="alert alert-danger alert-dismissible fade show"> <strong>There was a problem with your submission.  Please try again.</strong><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>');
                }
            }
        });
    }
});

最后是contact.php。请注意,这是不完整的。此时我正在尝试确认我正在获取 $_POST 数据:

<?php
if( empty($_POST )) {
    echo "Post is empty.";
} elseif( !empty($_POST)) {
    echo "Post is not empty.";
}

print_r($_POST);

$to = '';
$subject = 'Contact Form Submission';
$header = "From: ".$name." <".$email.">";

$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
$message = wordwrap($message, 70);

$response = '';

if ($name && $email && $message) {
    $response = 'success';
    mail($to, $subject, $header, $message);
} else {
    $response = 'error';
}

echo $response;
?>

正如我的问题标题所示,我没有得到数据。在 contact.php 处,我收到空的 post 消息,对于 print_r($_POST),我收到 Array ()。 post 数据没有到达,我不明白为什么。

编辑:我应该提到如果我 console.log($(this).serialize());就在 ajax 调用之前,我在控制台 window 中获得了正确的序列化数据。所以数据就在那里,并准备好在 ajax 调用之前进行。

opening a browser window and pointing it at localhost/mysite/contact.php. That's where the "Post is empty" message is echoed and where I get the "Array ()" output from my print_r($_POST)

这就是你正在做的事情:

  1. 通过在浏览器中打开文档向 HTML 文档发出 GET 请求 window
  2. 让 JavaScript 在 HTML 文档中向 contact.php
  3. 发出 POST 请求
  4. 检查对 POST 请求的响应
  5. 通过在浏览器中打开它向 contact.php 发出 GET 请求 window
  6. 查看对 GET 请求的响应

向 URL 发出 GET 请求您之前向 发出 POST 请求不会 显示您得到的响应 POST请求。

您有两个不同的请求和两个不同的响应。

如果您想查看对使用 Ajax 触发的请求的响应,则必须查看 那个 响应。您可以通过检查成功函数中的 response 变量或查看浏览器开发人员工具的“网络”选项卡来执行此操作。