form表单提交的那些事

208 阅读2分钟

项目开发中,使用的都是已经被封装的form组件。但他们也是基于原生form表单进行拓展的。有时候难免有一些莫名其妙的问题(其实是因为form表单的原生事件引起的)。

本篇文章就来说一说form提交那点事情。
(最近在看《明朝那些事儿》,作者写的挺好,很浅显,好看上头)

表单提交的两大属性

action: 表单提交的地址,URL(绝对路径或者相对路径) 相对路径的前缀使用当前页面的origin method: get or post。以什么请求方法请求URI

表单什么时候会提交?

inputbutton标签,属性type是image或者submit时,点击就会触发提交事件。

input标签默认type属性是 text,button标签默认type属性是 submit

所以啊,form里面一个不指定type属性的button被点击了,表单就会被提交

特殊的: 表单中只有一个<input>输入项时(label这类标签不算),并且标签type是text或者textarea时,输入框内回车就能触发表单提交事件

提交了什么内容?

<form action="/action_page.php">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="Doe" ><br><br>
  <select name="select" multiple="multiple">
  	<option>'love'</option>
    <option>'hate'</option>
  </select>
  <input type="submit"></input>
</form> 

表单值 = 输入标签name=value,多个输入标签的值用&连接。举个例子: fname=John&lname=Doe&select='love'&select='hate'

select是一个可多选的下拉选择框

提交之后发生了什么?

提交的过程其实就是用 [method]访问这样一串url,[action]?[表单值字符串]。页面会展示这串url返回的内容。

form表单没有制定action和method会怎么样? action为本页面url,method是get,表现就是页面重新刷新了

怎么阻止默认提交?

方法一:

<form onsubmit="myFunction(event)">
    Name : <input type="text"/>
    <input class="submit" type="submit">
  </form>
  <script>
  function myFunction(event){
    event.preventDefault();
    //code here
  }
  </script>

方法二:

onsubmit="return false"

以及基于Vue的方法

@submit.native.prevent

结语

感觉这是前端刀耕火种时代的程序员都会知道的知识了,但是由于现在前端的飞速发展,各种封装好的组件轮子层出不穷。新生代的程序员都很少知道这种原生标签的属性

参考文章

www.w3.org/MarkUp/html… developer.mozilla.org/en-US/docs/…