我做了一个简单的联系表单,我试图弄清楚如何更改页面上的html元素,以便在发送电子邮件时创建确认。截至目前,它只是在发送电子邮件时重新加载页面。如果名称部分为空或输入的电子邮件无效,我还希望错误消息在输入标签旁边显示为html元素。
这是我目前的代码:
HTML:
<div id="contact-content" class="format-div">
<form id="contact-form" action="/contact-form.php" method="post">
<label for="contact-name">Name</label>
<input type="text" id="contact-name" name="nameIn" placeholder="Enter
your name!">
<label for="email-address">E-mail</label>
<input type="text" id="email-address" name="emailIn" placeholder="Enter your e-mail address!">
<label for="contact-message">Message</label>
<textarea id="contact-message" name="messageIn" placeholder="All this space to fill with words..."
style="height:200px"></textarea>
<button type="submit" name="submit-mail"><i class="far fa-paper-plane"></i></button>
</form>
</div>
PHP:
if (isset($_POST['submit-mail'])) {
$name = $_POST['nameIn'];
$address = $_POST['emailIn'];
$message = $_POST['messageIn'];
$error = "";
if($name == '') $error .= 'Please fill in your name';
if (!filter_var($address, FILTER_VALIDATE_EMAIL)) $error .= 'The e-mail is invalid';
$mailTo = "[email protected]";
$subject = "FROM WEBSITE: ".$name;
$header = "Mail from: ".$name.", ".$address."\n\n";
mail($mailTo, $subject, $message, $header);
header("Location: index.html?mailsent");
}
在HTML标记内你可以这样:qazxsw我所以如果有错误它将显示在HTML标记内
你的html页面中的某个地方基本上在顶部也许你应该捕获GET变量,如果它已经设置。你也可以类似地显示错误。
<php if (isset($_POST['submit-mail'])) { echo $error; } ?>
此外,如果index.html不是具有表单代码的页面,那么它将无法访问错误变量。
将if(isset($_GET['mailsent'])){echo "Email Sent";} else if(isset($error)){echo $error;}
改为header("Location: index.html?mailsent");
并且因为你的html页面需要解析php,理想情况下它应该是一个php页面,即index.php
header("Location: index.html?error=".$error."&mailsent=");
当然将index.html页面重命名为index.php。如果你不想这样做,那么采取JavaScript方法。