在與server端進行數據傳遞時,通常會用到GET、POST方法進行參數提交,而參數提交的方式,通常取決於server端對數據的接收方式。
Query String Parameters
當發起一次GET請求時,參數會以url string的形式進行傳遞。即?
后的字符串則為其請求參數,並以&
作為分隔符。
如下http請求報文頭:
// General Request URL: http://foo.com?x=1&y=2 Request Method: GET // Query String Parameters x=1&y=2
Form Data
當發起一次POST請求時,若未指定content-type,則默認content-type為application/x-www-form-urlencoded。即參數會以Form Data的形式進行傳遞,不會顯式出現在請求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
當發起一次POST請求時,若content-type為application/json,則參數會以Request Payload的形式進行傳遞(顯然的,數據格式為JSON),不會顯式出現在請求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的方式來傳遞數據,則可以通過原生方法formData()來進行數據組裝,且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
,作為分隔參數,作用等同於&
。
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
的優勢還伴隨一些兼容性問題,詳細請參考文章結束的參考文獻。
參考文獻
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