2016-01-23 106 views
0

我已經在互聯網上搜索了所有內容,但我仍然感到困惑。我有一個表格,我提交併重定向到它自己。然後它將變量回顯到屏幕上。但是如何在用戶點擊刷新按鈕後阻止表單重新提交?這是可以實現的嗎?這裏是代碼重定向到同一頁面後避免表單重新提交php

  <!DOCTYPE HTML> 
     <html> 
     <head> 
     </head> 
     <body> 

     <?php 
     // define variables and set to empty values 
     $name = $email = $gender = $comment = $website = ""; 

     if ($_SERVER["REQUEST_METHOD"] == "POST") { 
      $name = test_input($_POST["name"]); 
      $email = test_input($_POST["email"]); 
      $website = test_input($_POST["website"]); 
      $comment = test_input($_POST["comment"]); 
      $gender = test_input($_POST["gender"]); 
      echo "<h2>Your Input:</h2>"; 
     echo $name; 
     echo "<br>"; 
     echo $email; 
     echo "<br>"; 
     echo $website; 
     echo "<br>"; 
     echo $comment; 
     echo "<br>"; 
     echo $gender; 
     } 
     if($_SERVER["REQUEST_METHOD"] == "GET") 
     { 
      header('Location: '. $_SERVER['PHP_SELF'] , true, 303); 
     } 

     function test_input($data) { 
      $data = trim($data); 
      $data = stripslashes($data); 
      $data = htmlspecialchars($data); 
      return $data; 
     } 
     ?> 

     <h2>PHP Form Validation Example</h2> 
     <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
      Name: <input type="text" name="name"> 
      <br><br> 
      E-mail: <input type="text" name="email"> 
      <br><br> 
      Website: <input type="text" name="website"> 
      <br><br> 
      Comment: <textarea name="comment" rows="5" cols="40"></textarea> 
      <br><br> 
      Gender: 
      <input type="radio" name="gender" value="female">Female 
      <input type="radio" name="gender" value="male">Male 
      <br><br> 
      <input type="submit" name="submit" value="Submit"> 
     </form> 

我是新來這....請幫助。

+0

你應該停止那種奇怪的習慣,有一個表格提交到生成腳本形成。我從來不明白爲什麼這樣做。它會導致很多問題。你有一個動作產生一個視圖,表單和處理表單的另一個動作。所以兩個單獨的腳本。簡單,高效和透明。 – arkascha

+0

即使我停止提交到相同的腳本,表單不斷重新提交頁面刷新。你能請教如何阻止?當提交錯誤數據時,我應該如何向用戶顯示錯誤消息? – user3485417

回答

0

簡單地說,如果提交值是存在的,沒有顯示提交按鈕或刪除的行爲提交按鈕這樣

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
     Name: <input type="text" name="name"> 
     <br><br> 
     E-mail: <input type="text" name="email"> 
     <br><br> 
     Website: <input type="text" name="website"> 
     <br><br> 
     Comment: <textarea name="comment" rows="5" cols="40"></textarea> 
     <br><br> 
     Gender: 
     <input type="radio" name="gender" value="female">Female 
     <input type="radio" name="gender" value="male">Male 
     <br><br> 
     <?php if(!isset($_POST["name"])) { ?> 
     <input type="submit" name="submit" value="Submit"> 
     <?php } ?> 
    </form> 
相關問題