繁体   English   中英

提交没有重定向的 HTML 表单并显示成功消息

[英]Submit a HTML form without redirection and showing a success message

我决定从 WordPress 网站切换到使用 HTML、CSS 和 JS 自制的网站,旨在提高性能。 到目前为止,依靠教程,我已经设法处理了几乎所有问题,但我无法让联系表单像在 WP 中那样工作。 到目前为止,它将我重定向到另一个显示成功消息的页面,这很丑陋。

基本上,我希望提交按钮做 3 件事: 1. 不要将我重定向到另一个页面。 2. 重置表格。 3. 显示成功消息。

在这里阅读了许多类似的问题,但由于我对 AJAX 完全不熟悉,因此最终决定发布此问题。 这是我的代码:

索引.html:

     <div>
        <form method="post" action="form.php" name="myForm">
          <input name="name" placeholder="Nombre" required>
          <input name="email" type="email" placeholder="Correo Electrónico" required>
          <textarea rows="10" name="message" placeholder="Mensaje" required></textarea>
          <input id="submit" name="submit" type="submit" value="Enviar Mensaje" class="boton-rojo">
        </form>
      </div>

并在 form.php 中:

<?php

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="De: $name \n Mensaje: $message";
$recipient = "contacto@mydomainname.cl";
$subject = "Mensaje desde el sitio web";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Tu consulta fue recibida";

?>

任何帮助将非常感激。

谢谢。

将 ID 放入您的表单

<form id='myForm'>
....
</form>

使用 jQuery(为了简单的代码)

   ....
   <script
      src="https://code.jquery.com/jquery-3.4.1.min.js"
      integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
      crossorigin="anonymous"></script>
</body>

使用 $.ajax


$('#myForm').submit(function(e) {

   e.preventDefault(); // prevent from submitting form directly

   $.ajax({
     url: 'form.php',
     method: 'post',
     data: $("#myForm").serializeArray() // convert all form data to array (key:value)
   })
   .done(function(response){
     alert(response); // show the response
     $("#myForm").reset(); // reset the form
   })
   .fail(function(error){
     alert(error); // show the error.
   });

})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM