form属性概述
- action 表单提交的url
- method 提交方式:post get
- name 表单的属性名
- enctype 提交数据的编码格式
enctype值介绍
在Form表单中,enctype表明提交数据的格式 用 enctype 属性指定将数据回发到服务器时浏览器使用的编码类型. 常见的编码方式:
1 application/x-www-form-urlencoded
:
概述: 当action为get,数据被编码为名称/值对,是标准的编码格式,也是默认的编码格式
格式:name1=value1&name2&value2 把form数据转换成一个字串,然后把
这个字串append到url后面,用?分割,加载这个新的url
2 multipart/form-data
:
概述:当action为post时,浏览器把form数据封装到http body中,然后发送到server。 如果没有type=file的控件,用默认的application/x-www-form-urlencoded就可以了。 但是如果有type=file的话,就要用到multipart/form-data了
。浏览器会把整个表单以控件为单位分割,并为每个部分加上ContentDisposition(form-data或者file),Content-Type(默认为text/plain),name(控件name)等信息,并加上分割符(boundary)。file或者img等发生上传文件时,设置entype = 'multipart/form-data',是上传二进制数据,它告诉我们传输的数据要用到多媒体传输协议,由于多媒体传输的都是大量的数据,所以规定上传文件必须是post方法,input的type属性必须是file。form里面的input的值以2进制的方式传过去,所以request就得不到值了。
表单提交
form表单的子组件input的type为submit
,点击即可提交。
表单提交不刷新页面
无刷新页面提交表单:表单可实现无刷新页面提交,无需页面跳转,如下,通过一个隐藏的iframe实现,form表单 的target设置为info,iframe的name名称也为info,form提交目标位当前页面iframe则不会刷新页面。
<form action="/url.do" method="post" target="targetIfr">
<input type="text" name="name"/>
</form>
<iframe name="targetIfr" style="display:none"></iframe>
form表单发送get请求
<form action="/b" method="get" name="form">
<!-- username -->
<label for="username">用户名称:</label>
<input type="text" name="username" id="username"/>
<br>
<!-- passowrd -->
<label for="passowrd">用户密码:</label>
<input type="password" name="passowrd" id="passowrd"/>
<br>
<!-- radio -->
<input type="radio" name="radio" id="radio1" value="raido1">
<label for="radio1">radio1</label>
<input type="radio" name="radio" id="radio2" value="raido2">
<label for="radio2">radio2</label>
<br>
<!-- checkbox -->
<input type="checkbox" name="checkbox" id="checkbox1" value="checkbox1">
<label for="checkbox1">checkbox1</label>
<br>
<input type="checkbox" name="checkbox" id="checkbox2" value="checkbox2">
<label for="checkbox2">checkbox2</label>
<br>
<!-- select -->
<label for="select">select:</label>
<select name="select" id="select">
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
<option value="ccc">ccc</option>
</select>
<br>
<!-- button -->
<input type="button" value="检查" onclick="check()">
<!-- 提交 -->
<input type="submit" value="提交">
</form>
form表单发送post请求
同上面代码一致,但是form里面的method属性要改成post
<form action="/get" method="get" name="form">
改为
<form action="/post" method="post" name="form">
表单发送前进行数据校验
获取表单填写的数据:form的name
.input的name
.value
前提条件: form填写了name的值。
const check = () => {
// 获取表单中的值可以通过 表单name.input中的name.value 获取。
console.log('username', form.username.value)
console.log('passowrd', form.passowrd.value)
console.log('radio', form.radio.value)
// checkbox的教研比较特殊,需要走特殊处理
let checkboxResult = []
for (const ele of document.getElementsByName('checkbox')) {
if(ele.checked) {
checkboxResult.push(ele.value)
}
}
console.log('checkbox', checkboxResult)
console.log('select', form.select.value)
}