Form 当中的 post 和 get

Form 当中的 post 和 get

From 最常见的两种方法有 Get 和 Post

Get 和 Post 本身都是发送请求到服务器,并等待获取相应的反馈。区别在于 Get 是请求服务器返回给定的资源,并且用户可以在浏览器中看到表格提交的内容。而 Post 是浏览器在请求响应时使用的一种方法,使用 Post 用户无法直接在浏览器 url 中直接看到提交的内容。

使用 Get 和 Post 的场景

Get:

  1. 指向服务端某个固定内容
  2. 请求的内容长度比较短
  3. URL 信息并不涉及安全隐私

Post:

  1. 提交的内容涉及安全隐私
  2. 提交的内容结构比较复杂,内容较多

使用了 Get 的 Form:

其中的 action 指代输入框中的内容将会被发送到的页面地址,method 指代提交的类型。当你提交了表格之后,浏览器输入框中的地址将会变成 www.foo.com/?say=Hi&to=Mom,服务器已经返回了你希望获取的页面资源,你会发现你可以在浏览器的 url 上直接看到自己在表格中提交的 “Hi”,“Mum”的内容。

<form action="http://foo.com" method="get">
  <div>
    <label for="say">What greeting do you want to say?</label>
    <input name="say" id="say" value="Hi">
  </div>
  <div>
    <label for="to">Who do you want to say it to?</label>
    <input name="to" id="to" value="Mom">
  </div>
  <div>
    <button>Send my greetings</button>
  </div>
</form>

HTTP请求

你会发现提交的内容 存储在 HTTP header中,body是空的

GET /?say=Hi&to=Mom HTTP/1.1
Host: foo.com

使用了 Post 的 Form:

Post 提交数据时的格式和 Get 基本相同,只是 Method 中改为 Post,

<form action="http://foo.com" method="post">
  <div>
    <label for="say">What greeting do you want to say?</label>
    <input name="say" id="say" value="Hi">
  </div>
  <div>
    <label for="to">Who do you want to say it to?</label>
    <input name="to" value="Mom">
  </div>
  <div>
    <button>Send my greetings</button>
  </div>
</form>

HTTP请求

你会发现提交的内容存储在 body 中,而不是header中

POST / HTTP/1.1
Host: foo.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 13

say=Hi&to=Mom

参考链接:

MDN 对于 Post 和 Get 的解释

MDN 对于 HTTP 的阐述

MDN 对于 form HTML的阐述

HTML