在與server端進行數(shù)據(jù)傳遞時桦山,通常會用到GET攒射、POST方法進行參數(shù)提交,而參數(shù)提交的方式恒水,通常取決于server端對數(shù)據(jù)的接收方式会放。
本文對幾種常見的參數(shù)提交方式進行歸納及簡述,這不是一篇科普文钉凌,不嚴謹處見諒咧最,僅供參考。
Query String Parameters
當發(fā)起一次GET請求時御雕,參數(shù)會以url string的形式進行傳遞矢沿。即?
后的字符串則為其請求參數(shù),并以&
作為分隔符酸纲。
如下http請求報文頭:
// General
Request URL: http://foo.com?x=1&y=2
Request Method: GET
// Query String Parameters
x=1&y=2
Form Data
當發(fā)起一次POST請求時捣鲸,若未指定content-type,則默認content-type為application/x-www-form-urlencoded闽坡。即參數(shù)會以Form Data的形式進行傳遞栽惶,不會顯式出現(xiàn)在請求url中。
如下http請求報頭:
// General
Request URL: http://foo.com
Request Method: POST
// Request Headers
content-type: application/x-www-form-urlencoded; charset=UTF-8
// Form Data
x=1&y=2
Request Payload
當發(fā)起一次POST請求時疾嗅,若content-type為application/json外厂,則參數(shù)會以Request Payload的形式進行傳遞(顯然的,數(shù)據(jù)格式為JSON)代承,不會顯式出現(xiàn)在請求url中汁蝶。
如下http請求報頭:
// General
Request URL: http://foo.com
Request Method: POST
// Request Headers
content-type: application/json; charset=UTF-8
// Request Payload
x=1&y=2
如果希望通過Form Data的方式來傳遞數(shù)據(jù),則可以通過原生方法formData()來進行數(shù)據(jù)組裝论悴,且content-type需要設置為multipart/form-data穿仪。
如下http請求報頭:
// General
Request URL: http://foo.com
Request Method: POST
// Request Headers
content-type: multipart/form-data; charset=UTF-8
// Request Payload
------WebKitFormBoundaryAIpmgzV8Ohi99ImM
Content-Disposition: form-data; name="x"
1
------WebKitFormBoundaryAIpmgzV8Ohi99ImM
Content-Disposition: form-data; name="y"
2
------WebKitFormBoundaryAIpmgzV8Ohi99ImM--
其中席爽,WebKitFormBoundaryAIpmgzV8Ohi99ImM
為瀏覽器隨機生成的boundary
,作為分隔參數(shù)啊片,作用等同于&
只锻。
application/x-www-form-urlencoded 和 multipart/form-data
The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.
multipart/form-data
的優(yōu)勢還伴隨一些兼容性問題,詳細請參考文章結束的參考文獻紫谷。
參考文獻
https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1
https://developer.mozilla.org/en-US/docs/Web/API/FormData
https://www.cnblogs.com/ChengWuyi/p/7117060.html
http://www.cnblogs.com/zourong/p/7340498.html
https://tools.ietf.org/html/draft-ietf-httpbis-p3-payload-14#section-3.2
https://stackoverflow.com/questions/23118249/whats-the-difference-between-request-payload-vs-form-data-as-seen-in-chrome
https://stackoverflow.com/questions/3508338/what-is-the-boundary-in-multipart-form-data