0

我有以下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 秒的弹出消息,例如“已添加记录”

4

2 回答 2

1

您正在寻找的内容与 PHP 无关,因为它是客户端......

有两种方法可以做到这一点:

  • 在您提交渲染弹出窗口并在 x 次后使用 javascript 将其删除...
  • 使用 ajax (javascript) 提交表单并解析结果,并在 javascript 中添加弹出窗口。
于 2012-07-02T15:03:53.287 回答
1

试试下面的。你也可以增强它。

在您的表单页面上添加用于弹出窗口的 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 动画

更新:

This assumes you will change your .html that contains the form file to .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
}

Also try out the suggested jQuery/Ajax method mentioned in the comments

于 2012-07-02T15:18:30.590 回答