我在我的网站上有一个联系表格,我最初成立了超过5年前.我记得它曾经直接在页面上的#form-messages div中显示错误/成功消息,但现在它将页面更改为send.php,显示未格式化的文本,而不是停留在联系人表单页面并在那里输出,我无法找到原因.难道event.preventDefault();不应该阻止改变页面的默认行为吗?

以下是相关的HTML语言:

<form id="ajax-contact" method="post" action="send.php">
    <div class="field">
        <label for="name">Name</label>
        <input type="text" id="name" name="name" autocomplete="name" required>
    </div>

    <div class="field">
        <label for="email">Email</label>
        <input type="email" id="email" name="email" autocomplete="email" required>
    </div>

    <div class="field">
        <label for="message">Message</label>
        <textarea id="message" name="message" required></textarea>
    </div>
    <div class="field">
        <button type="submit" class="button g-recaptcha" data-sitekey="X" data-callback='onSubmit' data-action='submit'>Send</button>
    </div>
</form>
<div id="form-messages"></div>

以下是联系人.js:

$(function() {
    // Get the form.
    var form = $('#ajax-contact');

    // Get the messages div.
    var formMessages = $('#form-messages');

    // Set up an event listener for the contact form.
    form.submit(function(event) {
        // Stop the browser from submitting the form.
        event.preventDefault();

        // Serialize the form data.
        var formData = form.serialize();

        // Submit the form using AJAX.
        $.ajax({
            type: 'POST',
            url: form.attr('action'),
            data: formData,
            captcha: grecaptcha.getResponse()

        }).done(function(response) {
            // Make sure that the formMessages div has the 'success' class.
            formMessages.removeClass('error');
            formMessages.addClass('success');

            // Set the message text.
            if (data.responseText !== '') {
                formMessages.text(data.responseText);
            } else {
                formMessages.text('Oops! An error occurred and your message could not be sent.');
            }

            // 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 occurred and your message could not be sent.');
            }
        });
    });
});

下面是send.php:

<?php
// If the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // If the Google Recaptcha box was clicked
    if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
        $captcha=$_POST['g-recaptcha-response'];
        $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=X&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
        $obj = json_decode($response);

        // If the Google Recaptcha check was successful
        if($obj->success == true) {
          // Clean up the data
          $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 for empty fields
          if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            http_response_code(400);
            echo "Oops! There was a problem with your submission. Please complete the form and try again.";
            exit;
          }

          // Set up the email to me
          $email_sender = "myname@mydomain.com";
          $email_receiver = "myname@gmail.com";
          $subject = "New message from $name";
          $email_content = "Name: $name\nEmail: $email\n\nMessage:\n$message\n";
          $email_headers = "From: $name <$email_sender>" . "\r\n" . "Reply-To: $name <$email>";

          // Set up the confirmation email
          $confirm_content =  "Hi $name,\n\nI'll get back to you as soon as I can. For your convenience, here is a copy of the message you sent:\n\n----------\n\n$message\n";
          $confirm_headers = "From: My Name <$email_sender>"  . "\r\n" . "Reply-To: My Name <$email_receiver>";

          // Send the email to me
          if (mail($email_receiver, $subject, $email_content, $email_headers)) {
            http_response_code(200);
            echo "Thank You! Your message has been sent, and you should have received a confirmation email. I'll get back to you as soon as I can!";
            // Send the confirmation email
            mail($email, "Thank you for your message!", $confirm_content, $confirm_headers);
          } 
          // If the server was unable to send the mail
          else {
            http_response_code(500);
            echo "Oops! Something went wrong, and we couldn't send your message. Please try again.";
          }
      } 
      // If the Google Recaptcha check was not successful    
      else {
        http_response_code(400);
        echo "Robot verification failed. Please try again.";
      }
  } 
  // If the Google Recaptcha box was not clicked   
  else {
    http_response_code(400);
    echo "Please click the reCAPTCHA box.";
  }      
} 
// If the form was not submitted
// Not a POST request, set a 403 (forbidden) response code.         
else {
  http_response_code(403);
  echo "There was a problem with your submission, please try again.";
}      
?>

推荐答案

问题似乎出在验证码的实施中.我最初遵循了谷歌自己的推荐到bind the challenge to the submit button,这似乎阻止了我阻止该按钮的默认行为.我最终放弃了使用不可见的reCAPTCHA的try ,回到了CheckBox实现,我终于让它工作了.

我的send.php没有变化.

我在HTML中所做的主要更改是,验证码现在附加到一个空的div,而不是附加到提交按钮:

<form id="ajax-contact" method="post" action="send.php">
    <div class="field">
        <label for="name">Name</label>
        <input type="text" id="name" name="name" autocomplete="name" required>
    </div>

    <div class="field">
        <label for="email">Email</label>
        <input type="email" id="email" name="email" autocomplete="email" required>
    </div>

    <div class="field">
        <label for="message">Message</label>
        <textarea id="message" name="message" required></textarea>
    </div>

    <div id="recaptcha" class="g-recaptcha" data-sitekey="x"></div>

    <div id="form-messages"></div>

    <div class="field">
        <button id="contact-submit" type="submit" class="button">Send</button>
    </div>
</form>

我的联系人.js几乎完全没有变化,除了我在.done部分设置消息文本的方式:

$(function() {
    var form = $('#ajax-contact');
    var formMessages = $('#form-messages');

    // Set up an event listener for the contact form.
    form.submit(function(event) {
        // Stop the default behavior from submitting the form.
        event.preventDefault();

        // Serialize the form data.
        var formData = form.serialize();

        // Submit the form using AJAX.
        $.ajax({
            type: 'POST',
            url: form.attr('action'),
            data: formData,
            captcha: grecaptcha.getResponse()
        }).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 occurred and your message could not be sent.');
            }
        });
    });
});

Javascript相关问答推荐

react 路由加载程序行为

if/else JavaScript中的条件行为

React Code不在装载上渲染数据,但在渲染上工作

将2D数组转换为图形

Google maps API通过API返回ZERO_RESULTS,以获得方向请求,但适用于Google maps

当试图显示小部件时,使用者会出现JavaScript错误.

v—自动完成不显示 Select 列表中的所有项目

显示图—如何在图例项上添加删除线效果?

如何调用名称在字符串中的实例方法?

JS,当你点击卡片下方的绿色空间,而它是在它的背后转动时,

第二次更新文本输入字段后,Reaction崩溃

当标题被点击时,如何使内容出现在另一个div上?

未捕获的运行时错误:调度程序为空

将基元传递给THEN处理程序

使用自动识别发出信号(&Q)

JavaScript将字符串数字转换为整数

如何检测当前是否没有按下键盘上的键?

如何创建一个for循环,用于计算仪器刻度长度并将其放入一个HTML表中?

如果我将高度设置为其内容的100%,则在Java脚本中拖动以调整面板大小时会冻结

已在EventListener中更新/更改异步的React.js状态对象,但不会导致组件重新呈现