概述
HTML中<form>
元素被用來表示一個區(qū)域,該區(qū)域中的控件,可以用來向服務(wù)器提交數(shù)據(jù)。
常用屬性
-
action
: 表示處理form的URL。 -
method
: 表示提交表單的方法 -
enctype
: 提交form給服務(wù)器的內(nèi)容的 MIME 類型。-
application/x-www-form-urlencoded
: 如果屬性未指定時的默認值 -
multipart/form-data
: 這個值用于一個 type 屬性設(shè)置為file
的 <input> 元素 text/plain (HTML5)
-
target
: 一個名字或者說關(guān)鍵字,用來指示在提交表單之后,在哪里顯示收到的回復(fù)。
-
method
方法中 POST
和GET
區(qū)別
GET是向服務(wù)器獲取數(shù)據(jù),POST是向服務(wù)器上傳數(shù)據(jù)。
-
數(shù)據(jù)提交方式
使用GET,數(shù)據(jù)被拼接成URL向服務(wù)器發(fā)送請求 如
http://test.com/login?user=admin&password=123
使用POST, 數(shù)據(jù)被包裝在請求的body中向服務(wù)器發(fā)送請求。 安全性
POST的安全性高于GET,因為GET的數(shù)據(jù)會直接顯示在URL里面
- 編碼
GET只能發(fā)送ASCII字符,POST可以則可以發(fā)送整個ISO 10646中的字符。在Form中的enctype中,當(dāng)屬性為`multipart/form-data`,(form 數(shù)據(jù)中包含文件),只能使用POST
-
提交的數(shù)據(jù)長度
GET提交的長度為2083個字符,受制于URL的長度。
-
緩存
GET提交的記錄會被瀏覽器緩存。在歷史記錄中。
表單常用的input標(biāo)簽
form表單的作用可以收集信息,提交給網(wǎng)站后臺。常用的input標(biāo)簽如下:
-
text
: 單行字段。 -
password
: 一個值被遮蓋的單行文本字段,使用maxlength
可以指定輸入的值的最大長度。 -
checkbox
: 復(fù)選框。使用value
屬性定義控件被提交的值。使用checked
屬性表示控件是否被選擇。 -
radio
: 單選按鈕,使用value
屬性定義控件被提交的值。在同一個”單選按鈕組“中,所有單選按鈕的 name 屬性使用同一個值; 一個單選按鈕組中是,同一時間只有一個單選按鈕可以被選擇。 -
file
: 可讓用戶選擇文件。accept
屬性控制可以選擇文件的類型。 -
hidden
: 不顯示在頁面的上的控件,但是值會被提交到服務(wù)器。 -
button
: 無缺省行為的按鈕。 -
submit
: 用于提交表單的按鈕 -
reset
: 用于將表單所有內(nèi)容設(shè)置為缺省值的按鈕
代碼示例
<form action="/userInfo" method="post"> <div class="name"> <label for="name">姓名:</label> <input type="text" id="name" name="name" placeholder="用戶名"> </div> <div class="password"> <label for="password">密碼:</label> <input type="password" id="password" name="password" placeholder="輸入密碼"> </div> <div class="gender"> <label for="gender">性別:</label> <input type="radio" name="gender" value="male">男 <input type="radio" name="gneder" value="female">女 </div> <div class="sex"> <label for="sex">取向:</label> <input type="radio" name="sex" value="male">男 <input type="radio" name="sex" value="female">女 </div> <div class="hobby"> <label for="hobby">愛好:</label> <input type="checkbox" name="hobby" value="dota">dota <input type="checkbox" name="hobby" value="旅游">旅游 <input type="checkbox" name="hobby" value="寵物">寵物 </div> <div class="comment"> <label for="comment">評論:</label> <textarea name="comment" id="comment" cols="30" rows="10" placeholder="評論"></textarea> </div> <div class="myCar"> <label for="myCar">我的Car:</label> <select name="myCar" id="myCar"> <option value="bmw">寶馬</option> <option value="benz" selected>奔馳</option> <option value="audi">奧迪</option> </select> </div> <input type="submit" value="提交"> </form>
其他
-
<label>
元素中for
屬性表示,當(dāng)點擊label時,for
對應(yīng)id的元素會被focus。
-