浏览器可以通过 form 表单提交的方式向服务器发送数据, 之前都没有特别注意仔细了解下表单的相关属性,表单控件相关特性,此文为参考别人博客的一个自我总结,供后续参考。
form表单常用属性:
- action: url地址,服务器接受表单数据的地址;
- method: 提交到服务器的 http 方法,一般为 post 和 get;
- name: 最好保持 name 属性唯一;
- enctype: 表单数据提交时使用的编码类型,默认使用"application/x-www-form-urlencoded",如果使用 post 方法,请求头中 content-type指定值即为此属性值。如果表单中有上传文件的 input 控件,编码类型需要使用"multipart/form-data", 才能完成传递文件数据。
表单提交规则:
- 具有disabled属性的字段不会被提交
- 不具有name属性的字段不会被提交
- 同名的name属性会发生覆盖,radio和checkbox除外
- form指向其他表单的字段,不会被本表单提交
表单元素 | type | 规则 |
---|---|---|
input | button | 永远不提交 |
input | checkbox | 只在勾选后提交 |
input | file | 永远提交,即使为空值 |
input | hidden | 永远提交,即使为空值 |
input | image | 永远提交,即使为空值 |
input | radio | 只在勾选后提交,如果一组Radio没有任何勾选,全部不提交。 |
input | reset | 永远不提交 |
input | submit | 点击哪个按钮,则提交这个按钮的值,其他的SUBMIT按钮值都不提交。如果表单的提交行为是由JavaScript脚本触发的,则不提交任何值。 |
input | text | 永远提交,即使为空值 |
button | button | 永远不提交 |
button | reset | 永远不提交 |
button | submit | 点击哪个按钮提交表单,则提交这个按钮的值。 |
textarea | 永远提交,即使为空值 | |
select | 永远提交,即使为空值 |
浏览器提交表单时,会执行如下步骤:
- 识别出表单中表单元素的有效项(即根据上述表单提交规则来确定)作为提交项(successfull controls)
- 构建一个表单数据集(form data set)
- 根据 form 表单中 enctype 属性的值作为 content-type对数据集进行编码
- 根据 form 表单中的 action 属性和 method 属性向指定的地址发送数据
提交方法一般用"post" 或 "get":
- get: 表单数据会被encodeURIComponent后以参数形式:name1=value1&name2=value2 附带在 url?后面发送给服务器,并在url中显示出来;
- post: content-type 默认"application/x-www-form-urlencoded" 对表单数据进行编码,数据字段以键值对在 http请求体中发送给服务器;如果 enctype 属性值为"multipart/form-data",则以消息的形式发送给服务器。
enctype 指定的 content-type有:
- application/x-www-form-urlencoded: 默认加密方式,name value pair以name=value&name2=value2形式提交,其中的特殊字符被转义,具体见https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4;
- multipart/form-data: 一般用于提交文件,二进制数据。
表单序列化
通过JavaScript异步提交(ajax 提交)表单时,如果需要按照上面的规则去获取表单数据,jquery提供了 <span style="background-color: #FFFF00">serialize()</span>
和<span style="background-color: #FFFF00"> serializeArray()</span>
两个方法。使用该方法会取得和原生表单一致的提交字段。
代码示例
<form action="/api/form/submit" method="post" name="myForm">
<input type="checkbox" name="checkbox" checked>
<input type="checkbox" name="checkbox" checked>
<select name="select">
<option>option1</option>
<option selected>option2</option>
<option>option3</option>
</select>
<input type="text" name="text">
<input type="radio" name="radio" checked>
<button type="submit">提交表单</button>
</form>
post 方法提交
get 方法提交
表单中有input type="file" 类型元素
<form action="/api/form/submit" method="get" name="myForm">
<input type="checkbox" name="checkbox" checked>
<input type="checkbox" name="checkbox" checked>
<select name="select">
<option>option1</option>
<option selected>option2</option>
<option>option3</option>
</select>
<input type="text" name="text">
<input type="file" name="file">
<input type="radio" name="radio" checked>
<button type="submit">提交表单</button>
</form>
has file
网友评论