當用戶在 HTML 表單 (HTML Form) 中輸入信息並提交之后,有兩種方法將信息從瀏覽器傳送到 Web 服務器 (Web Server)。
一種方法是通過 URL,另外一種是在 HTTP Request 的 body 中。
前一種方法,我們使用 HTML Form 中的 method = "get"
,后一種方法我們使用 HTML Form 中的 method ="post"
。
例句如下:
<form action = "..." method = "get">
<from action = "..." method = "post">
通過 get 或者 post 方法都可以獲得 Form 的數據,兩者主要區別在於以下幾方面:
Get
- URL 改變,在URL 里顯示 HTML Form 參數的 name/value 值。
- 只適合有少量參數的 HTML Form,因為 URL 長度有字符限制,不能無限長。
- 涉及安全性的信息,比如用戶密碼,不能用 get,因為會在 URL 上顯示,不安全。
Post
- URL 不改變,不在 URL 里顯示 HTML Form 的數據。
- Form 提交的信息沒有長度限制。
- 涉及安全性的信息,如用戶密碼,應采用 post 方式。
我們看看 get 是如何提交 Form 數據的。我們先寫一個 HTML 文件,如下:
<html> <head><title>Blablar.com HTML Form Method Get Example</title></head> <body> <form action ="get.php" method ="get"> Name: <input type="text" name="username" /> <input type ="submit" value="ok" /> </form> </body> </html>
該 HTML 的顯示界面如下:
當你在這個 HTML 文件的表單文本框輸入框里輸入姓名,比如 "Jacky",然后鼠標點擊ok 按鈕,會跳轉到 get.php,在 get.php 里會顯示如下圖。
你可以看到在瀏覽器地址欄里的URL是:
http://localhost:8080/get.php?username=Jacky
注意get.php
后面的字符串 ?username=Jacky
,這是一對 name/value 數據,前面加一個問號。
如果你將 form 改成 method = "post"
,你在瀏覽器地址欄就看不到這對 name/value 數據,而只有:
http://localhost:8080/get.php
使用 get 時,第一對 name/value 值前要加一個問號?
,以后每對 name/value 值則要用 &
分開。比如一個 form中有三個參數,如下:
<form action ="u.php" method ="get"> Name: <input type="text" name="username" /> Age: <input type="text" name="age" /> Gender: <input type="text" name="gender" /> <input type ="submit" value="ok" /> </form>
比如你在Name 項填寫Jacky,Age項填寫50,Gender項填了male,提交之后的 URL 顯示為:
http://localhost:8080/get.php?username=Jacky&age=50&gender=male