form提交的幾種方式

背景


一直使用postman做爲restful接口的調試工具,可是針對post方法的幾種類型,始終不明白其含義,今天完全瞭解了下javascript

form提交的來源

html頁面上的form表單html

<form action="/handling-page" method="post">
  <div>
    <label for="name">用戶名:</label>
    <input type="text" id="name" name="user_name" />
  </div>
  <div>
    <label for="passwd">密碼:</label>
    <input type="password" id="passwd" name="user_passwd" />
  </div>
  <div>
    <input type="submit" id="submit" name="submit_button" value="提交" />
  </div>
</form>

GET

提交的數據格式跟java

元素的method屬性有關。該屬性指定了提交數據的 HTTP 方法。若是是 GET 方法,全部鍵值對會以 URL 的查詢字符串形式,提交到服務器,好比/handling-page?user_name=張三&user_passwd=123&submit_button=提交。下面就是 GET 請求的 HTTP 頭信息。

GET /handling-page?user_name=張三&user_passwd=123&submit_button=提交
Host: example.com

POST

若是是 POST 方法,全部鍵值對會鏈接成一行,做爲 HTTP 請求的數據體發送到服務器,好比user_name=張三&user_passwd=123&submit_button=提交。下面就是 POST 請求的頭信息。api

POST /handling-page HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 74

user_name=張三&user_passwd=123&submit_button=提交

FormData(XMLHttpRequest.sendf方法)

表單數據以鍵值對的形式向服務器發送,這個過程是瀏覽器自動完成的。可是有時候,咱們但願經過腳本完成過程,構造和編輯表單鍵值對,而後經過XMLHttpRequest.send()方法發送。瀏覽器原生提供了 FormData 對象來完成這項工做。瀏覽器

//獲取表單對象
var myForm = document.getElementById('myForm');
var formData = new FormData(myForm);

//提交表單
var xhr = new XMLHttpRequest();
xhr.open('POST', '/handler/new', true);
xhr.onload = function () {
  if (xhr.status !== 200) {
    console.log('An error occurred!');
  }
};

xhr.send(formData);

enctype 屬性

表單可以用四種編碼,向服務器發送數據。編碼格式由表單的enctype屬性決定。服務器

1.腳本提交的post方法:GET 方法

若是表單使用GET方法發送數據,enctype屬性無效。
數據將以 URL 的查詢字符串發出。restful

?foo=bar&baz=The%20first%20line.%0AThe%20second%20line.

2.腳本提交的post方法:application/x-www-form-urlencoded

若是表單用POST方法發送數據,並省略enctype屬性,那麼數據以application/x-www-form-urlencoded格式發送(默認值)。app

發送的 HTTP 請求以下。工具

Content-Type: application/x-www-form-urlencoded

foo=bar&baz=The+first+line.%0D%0AThe+second+line.%0D%0A

上面代碼中,數據體裏面的%0D%0A表明換行符(\r\n)。post

3.text/plain

若是表單使用POST方法發送數據,enctype屬性爲text/plain,那麼數據將以純文本格式發送。

Content-Type: text/plain

foo=bar
baz=The first line.
The second line.

對應postman的raw,能夠自定義格式

4.multipart/form-data

若是表單使用POST方法,enctype屬性爲multipart/form-data,那麼數據將以混合的格式發送。

Content-Type: multipart/form-data; boundary=---------------------------314911788813839

-----------------------------314911788813839
Content-Disposition: form-data; name="foo"

bar
-----------------------------314911788813839
Content-Disposition: form-data; name="baz"

The first line.
The second line.

-----------------------------314911788813839--

這種格式也是文件上傳的格式。

postman中對應的form-data

參考

https://wangdoc.com/javascript/bom/form.html
https://www.getpostman.com/docs/v6/postman/sending_api_requests/requests

相關文章
相關標籤/搜索