通过 php 文件操作索引中的 HTML 元素.html



我制作了一个简单的联系表格,我正在尝试弄清楚如何更改页面上的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 = "myemail@mysite.come";
$subject = "FROM WEBSITE: ".$name;
$header = "Mail from: ".$name.", ".$address."nn";
mail($mailTo, $subject, $message, $header);
header("Location: index.html?mailsent");
}

我要用错误消息做什么

在 HTML 标签中,您可以放置以下内容:<php if (isset($_POST['submit-mail'])) { echo $error; } ?>所以如果有错误,它将显示在 HTML 标签中

在你的html页面中的某个地方,基本上在顶部,也许你应该抓住GET变量,如果它被设置的话。 您也可以类似地显示错误。

if(isset($_GET['mailsent'])){echo "Email Sent";} else if(isset($error)){echo $error;}

此外,如果index.html不是具有表单代码的页面,那么它将无法访问错误变量。

header("Location: index.html?mailsent");更改为header("Location: index.html?error=".$error."&mailsent=");

而且因为你的HTML页面需要解析PHP,理想情况下它应该是一个PHP页面,即索引.php

header("Location: index.php?error=".$error."&mailsent=");

当然,将 index.html 页面重命名为 index.php.如果您不想这样做,请采用 JavaScript 方法。

最新更新