2016-03-18 98 views
0

我在寫一個簡單的HTML表單來測試我構建的PHP數據庫應用程序。它可驗證地向數據庫添加項目,但拒絕創建顯示消息。任何人都可以解釋發生了什麼?爲什麼不顯示消息?

這裏是我的代碼:

<!DOCTYPE html> 
 
<html lang="en-us"> 
 
    <head> 
 
     <meta charset="utf-8"/> 
 
     <style> 
 
      textarea { 
 
       width: 90%; 
 
       height: 300px; 
 
       border-radius: 12px; 
 
      } 
 
      
 
      form { 
 
       max-width: 50%; 
 
       top: 10px; 
 
       bottom: 10px; 
 
       padding: 1%; 
 
       margin: auto; 
 
       height: 880px; 
 
       background: radial-gradient(#888, #999, #aaa, #bbb, #ccc, #ddd, #eee); 
 
      } 
 
      
 
      label[for=description] { 
 
       display: block; 
 
      } 
 
      
 
      body { 
 
       background: steelblue; 
 
      } 
 
     </style> 
 
    </head> 
 
    <body> 
 
     <form> 
 
      <label for="name">Name:</label> 
 
      <input id="name" name="name"/> 
 
      <hr/> 
 
      <label for="description">Description:</label> 
 
      <textarea id="des" name="cost"></textarea> 
 
      <hr/> 
 
      <button onclick="sendData()">Create Class</button> 
 
     </form> 
 
     <script> 
 
      var n; 
 
      var descript; 
 
      function sendData() { 
 
       n = document.getElementById("name").value; 
 
       descript = document.getElementById("des").value; 
 
       var http = new XMLHttpRequest(); 
 
       http.onreadystatechange = function() { 
 
        if (http.readyState == 4 && http.status == 200) { 
 
         response(http.responseText); 
 
        } 
 
       }; 
 
       http.open("GET", "class_add.php?name=" + name + "&descript=" + descript, true); 
 
       http.send(); 
 
      } 
 

 
     /*This is supposed to make the display msg*/ function response(txt) { 
 
       var p = document.createElement("p"); 
 
       p.innerHTML = txt; 
 
       p.style.fontSize = "30px"; 
 
       p.style.fontFamily = "Comic Sans MS"; 
 
       p.style.color = "magenta"; 
 
       document.body.appendChild(p); 
 
      } 
 
     </script> 
 
    </body> 
 
</html>

回答

2

您提交的表單和頁面重新加載本身並消滅任何變化。提交按鈕元素的default type,因此將其更改爲按鈕,因此點擊它將不會提交表單:

<button type="button" onclick="sendData()">Create Class</button> 
+0

非常感謝!我以前從來不知道。 –

+0

@NullSpark你應該將它標記爲答案,因爲它回答了你的問題。 –