【发布时间】:2017-06-08 10:39:02
【问题描述】:
我创建了一个联系表单,以便用户可以向我们发送电子邮件。但是,每次我单击以发送电子邮件时,它也会在单击时刷新页面。这是一个单页网站。
我尝试了以下建议的修复:How do I make an HTML button not reload the page
使用<button> 元素或<input type="button"/>。以及建议的修复:prevent refresh of page when button inside form clicked
通过添加onclick="return false;"。
这两个修复程序都会阻止按钮在单击时刷新页面,但是,它也会阻止联系表单实际工作并且不再向我们发送电子邮件。
我还更新了我的 PHP 以反映类型的名称更改。
我的 PHP 是:
<?php
if(isset($_POST['submit'])){
$to = "example@example.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
}
?>
我的 HTML 是:
<form action="" method="post" id="contactForm">
<input type="text" name="name" id="name" placeholder="Name...">
<input type="text" name="email" id="email" placeholder="Email...">
<p><br></p>
<textarea name="message" id="message" cols="40" rows="3" spellcheck="true" placeholder="Message..."></textarea>
<p><br></p>
<button type="submit" id="submit" name="submit" onclick="return false;">Send Message</button>
</form>
这目前适用于发送电子邮件,但不会阻止它刷新页面。将不胜感激任何帮助它为什么这样做..
编辑:
我已经尝试了一些使用 AJAX 的不同选项,因为有人建议这是最好的选择。一切都成功地阻止了页面刷新,但所有选项再次阻止了我的联系表格的工作。我试过了:
1:
$(function() {
$('#contactForm').on('submit', function(e) {
$.post('index.php', $(this).serialize(), function (data) {
// This is executed when the call to mail.php was succesful.
// 'data' contains the response from the request
}).error(function() {
// This is executed when the call to mail.php failed.
});
e.preventDefault();
});
});
2:
$("#contactForm").submit(function(e) {
e.preventDefault();
});
3:
我也尝试了 Harsh Panchal 提供给我的答案。
【问题讨论】:
-
你似乎在寻找的东西叫做 AJAX。
-
啊!谢谢@FirstOne - 在您提出建议后刚刚对此进行了搜索,并有几个选项可供测试。欣赏评论。
-
@thickguru 请检查答案,如果您有任何问题,请告诉我
-
SagarV 我觉得投反对票和重复是因为您的答案未被接受。有点有趣 xD ......我没有用视频回复你,因为@aendeerei 有一个更好的答案。不知道为什么你也对他的回答投了反对票。咸的。
-
我没有投反对票。这不是我这边的事情。骗子,我,有时访问旧帖子,我看到了那个。然后我想起了这个帖子。我检查了开放赏金是否存在。如果它存在,我可以将其标记为 mod 的唯一选项。但由于它不存在,我提出了一个欺骗标志。