让页面上的表单向同一页面发送信息的最佳方式是什么?


what's the best way to have a form on a page send information to the same page

例如下面的文件是sampage .php

    <!DOCTYPE html>
    <html lang="en">
    <head><title>Personal Information</title></head>
    <body>
    <?php
         if(!empty($_POST))
         {
              echo $_POST['var'].'<br />';
              //do a bunch of stuff
              ...
              echo "Inserted into database succesfully! You will now be redirected.<meta http-equiv=refresh content=4;url=database.php><br /></body></html>";//meta refresh gets rid of old POST data
              exit;
         }
     ?>
Add another entery:<br />
<form method="POST" action="SamePage.php"><--!It sends the information to itself-->
name: <input type="text" name="name" size="10" maxlength="25" /><br />
telephone: <input type="text" name="telephone" size="10" maxlength="25" /><br />
birthday: <input type="text" name="birthday" size="10" maxlength="25" /><br />
<input type="submit" value="add" />
<input type="reset" value="clear" />
</form>
</body>
</html>

在那里有退出不是很好,有时我不想刷新页面,但它必须完成,以防用户按下浏览器上的刷新,并且再次发送相同的POST数据,并且事情变得混乱。有人能想到更好的办法吗?

最好是将表单发送到另一个页面,然后重新加载您的页面…但是如果你不想要,你可以:

  • 使用AJAX
  • 把你所有的HTML代码放在{}符号之间
  • 使用模板(避免PHP和HTML混合)