【发布时间】:2020-10-29 02:53:50
【问题描述】:
我是第一次使用 Php 并尝试与我们联系表格。我已经在 html 代码中使用内联 php 制作了表单,并将文件保存为 .php 并且它可以工作。现在看起来真的很难看,而且我的 nodejs 服务器不提供我的 php 文件,所以我试图将 php 代码取出到一个单独的文件中。
所以现在我有两个文件 -
- index.html 格式
- mail.php
index.html
<h2>PHP FORM </h2>
<form action="mail.php" method="POST">
<label for="user">Name</label>
<input type="text" id="user" name="users-name"><br>
<label for="email">Email</label>
<input type="email" id="email" name="users-email"><br>
<label for="cars">Category</label>
<select name="users-cat" id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select><br>
<label for="subject">Subject</label>
<input type="text" id="subject" name="users-subject"><br>
<label for="msg">Message</label>
<input type="text" id="msg" name="users-message"><br>
<input type="submit">
</form>
mail.php是这样的-
<?php
if (isset($_POST['users-name']) ||
isset($_POST['users-email']) ||
isset($_POST['users-subject'])) {
$admin_email = "username@gmail.com";
$name = stripslashes($_POST['users-name']);
$subject = stripslashes($_POST['users-subject']);
$email = stripslashes($_POST['users-email']);
$category = stripslashes($_POST['users-cat']);
$message = stripslashes($_POST['users-message']);
//send email
$maiL_status = mail($admin_email, "$subject", "Contact Email: " . $email . "\n" . "Name: " . $name . "\n" . "Category: " . $category . "\n" . "Message: " . $message);
//Email response
echo '<h4 class="text-center">THANK YOU.</h4>';
echo '<h6 class="text-center">Your message is now being processed.</h6>';
echo '<h6 class="text-center">We will get back to you promptly.</h6>';
header("Location: index.html?message=ThankYou");
}else{
echo '<h4 class="text-center">Problem</h4>';
}
?>
所以我的问题是 - 我如何使用 mail.php 提交我的表单并重定向回带有消息的 html 页面。我开放使用 Jquery 或 javascript。我想将回显响应发送回 html 页面并在 html 页面中显示消息。
我浏览了很多 stackvoerflow 帖子,但我无法弄清楚
编辑:
我已经使用 javascript 解决了这个问题 -
let msg = window.location.href;
msg = msg.split('=')[1];
console.log(msg);
if(msg!=null){
$('#form_id').hide();
$('#repos').show();
$('#repos').text(msg);
}
【问题讨论】:
-
您应该查看“AJAX”——您在后台使用 javascript 将表单发布到 PHP 脚本,并在 javascript 中获取结果,然后使用 javascript 显示结果,以及在他们看到您的结果消息后,可能会将用户导航到新页面。这是一种更现代的方式。另一种选择是使用
index.php?showWelcomeMessage=1之类的查询参数重定向用户,并在存在该查询参数时有条件地显示您的消息。
标签: javascript php html forms