我有以下html形式:
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
这是.php文件:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
如何获得在提交记录后显示 2 秒的弹出消息,例如"已添加记录"
请尝试以下操作。您也可以增强它。
在表单页面上添加弹出窗口的 css
//adduser.php
#popup {
visibility: hidden;
background-color: red;
position: absolute;
top: 10px;
z-index: 100;
height: 100px;
width: 300px
}
和您的弹出式div
//still adduser.php
<div id="popup">
Record added successfully
</div>
成功后使用 PHP 输出此内容
//still adduser.php - probably at the bottom of the page
<?php
$recordAdded = false;
if(isset($_GET['status'] && $_GET['status'] == 1)
$recordAdded = true;
if($recordAdded)
{
echo '
<script type="text/javascript">
function hideMsg()
{
document.getElementById("popup").style.visibility = "hidden";
}
document.getElementById("popup").style.visibility = "visible";
window.setTimeout("hideMsg()", 2000);
</script>';
}
?>
脚本取消隐藏弹出窗口以显示消息,然后在 2 秒后将其隐藏
您可以使用jQuery增强动画,并使用CSS增强div
更新:
这假定您将包含表单文件的.html
更改为.php
//insert.php
if (!mysql_query($sql,$con))
{
//die('Error: ' . mysql_error());
}
else
{
// 1 record added
//if number of rows affected > 0
header("Location: backtoform.php?status=1"); //redirects back to form with status=1
}
还可以尝试注释中提到的建议的jQuery/Ajax方法
您正在寻找的内容与PHP无关,因为它是客户端...
有两种方法可以做到这一点:
- 提交后,渲染弹出窗口并在 X 次后使用 JavaScript 将其删除...
- 使用 Ajax (JavaScript) 提交表单并解析结果,并在 JavaScript 中添加弹出窗口。