目标: form表单的基本使用
1. form表单的基本使用
1.1 什么是表单
1.2 表单的组成部分
1.3 <form>标签的属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="/login" target="_blank" method="post">
<input type="text" name="email_or_mobile" />
<input type="password" name="password" />
<button type="submit">提交</button>
</form>
</body>
</html>
1. action
action 属性用来规定当提交表单时,向何处发送表单数据。
action 属性的值应该是后端提供的一个 URL 地址,这个 URL 地址专门负责接收表单提交过来的数据。
当 <form> 表单在未指定 action 属性值的情况下,action 的默认值为当前页面的 URL 地址。
注意:当提交表单后,页面会立即跳转到 action 属性指定的 URL 地址
2. target
target 属性用来规定在何处打开 action URL。
它的可选值有5个,默认情况下,
target 的值是 _self,表示在相同的框架中打开 action URL。
3. method
method 属性用来规定以何种方式把表单数据提交到 action URL。
它的可选值有两个,分别是 get 和 post。
默认情况下,method 的值为 get,表示通过URL地址的形式,把表单数据提交到 action URL。
4. enctype
enctype 属性用来规定在发送表单数据之前如何对数据进行编码。
它的可选值有三个,默认情况下,enctype 的值为 application/x-www-form-urlencoded,表示在发送前编码所有的字符。
注意:
在涉及到文件上传的操作时,必须将 enctype 的值设置为 multipart/form-data
如果表单的提交不涉及到文件上传操作,则直接将 enctype 的值设置为 application/x-www-form-urlencoded 即可!
1.4 表单的同步提交及缺点
1. 什么是表单的同步提交
通过点击 submit 按钮,触发表单提交的操作,从而使页面跳转到 action URL 的行为,叫做表单的同步提交。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="/login">
<input type="text" name="user_name" />
<input type="password" name="password" />
<button type="submit">提交</button>
</form>
</body>
</html>
2. 表单同步提交的缺点
① <form>表单同步提交后,整个页面会发生跳转,跳转到 action URL 所指向的地址,用户体验很差。
② <form>表单同步提交后,页面之前的状态和数据会丢失。
思考:如何解决上述两个问题?
3. 如何解决表单同步提交的缺点
如果使用表单提交数据,则会导致以下两个问题:
① 页面会发生跳转
② 页面之前的状态和数据会丢失
解决方案:表单只负责采集数据,Ajax 负责将数据提交到服务器。
更多Ajax内容:
黑马前端专栏干货多多,关注再学,好方便~
2023年前端学习路线图:课程、源码、笔记,技术栈另外此线路图实时更新!需要课后资料的友友们,可以直接告诉我喔~