[英]How to send data in the HTTP request body when using an HTML form?
The HTTP spec says that a POST request can contain an arbitrary body of data. HTTP规范说POST请求可以包含任意数据体。
An HTML form
element can POST to a URL and may contain input
elements, but those input
elements get turned into a query string. HTML
form
元素可以POST到URL并且可以包含input
元素,但这些input
元素将变为查询字符串。
How can I get a form
to also send along data in the body of the HTTP POST request that it sends when its submit button is pressed? 我如何获得一个
form
以便在按下提交按钮时发送的HTTP POST请求正文中的数据?
The HTTP spec says that a POST request can contain an arbitrary body of data.
HTTP规范说POST请求可以包含任意数据体。
That's correct. 那是对的。 There are in turn however several specifications of the format of that data.
然而,该数据的格式又有几种规格。 In case of HTML forms, most commonly used is
application/x-www-form-urlencoded
, followed by multipart/form-data
. 对于HTML表单,最常用的是
application/x-www-form-urlencoded
,后跟multipart/form-data
。 You can set it via the enctype
attribute of the HTML <form>
element. 您可以通过HTML
<form>
元素的enctype
属性进行设置。 See also chapter 17.13.4 Form Content Types of the HTML specification. 另请参见第17.13.4节HTML规范的表单内容类型 。
An HTML form element can POST to a URL and may contain input elements, but those input elements get turned into a query string.
HTML表单元素可以POST到URL并且可以包含输入元素,但这些输入元素将变为查询字符串。
That's indeed how application/x-www-form-urlencoded
works. 这确实是
application/x-www-form-urlencoded
工作方式。 Do note that this query string actually represents the whole HTTP request body! 请注意,此查询字符串实际上代表整个HTTP请求正文! So the request body is definitely not empty as you seem to think.
因此,您似乎认为请求正文绝对不是空的。
How can I get a form to also send along data in the body of the HTTP POST request that it sends when its submit button is pressed?
我如何获得一个表单,以便在按下提交按钮时发送的HTTP POST请求正文中的数据?
It thus actually already does that. 因此它实际上已经这样做了。 If you intented to send a copy of the HTML DOM tree representation of the form itself, as somewhat hinted in the previous statement, then you can achieve that with a little help of JavaScript as follows:
如果您打算发送表单本身的HTML DOM树表示的副本,如前面的语句中稍微暗示的那样,那么您可以通过JavaScript的一点帮助实现以下目的:
<form onsubmit="this.source.value=this.outerHTML">
...
<input type="hidden" name="source" />
<input type="submit" />
</form>
The whole HTML DOM tree representation of the form is then in string format available as request parameter with name source
. 然后,表单的整个HTML DOM树表示形式为字符串格式,可用作名称
source
请求参数。
Use javascript to send an ajax request when the button is pressed and cancel the form submission. 按下按钮时使用javascript发送ajax请求并取消表单提交。 Form submits will always be name/value pairs.
表单提交将始终是名称/值对。 XForms can send customized data but if this is for public use it'll be years before XForms is supported by the majority of browsers in use, if ever.
XForms可以发送自定义数据,但如果这是供公众使用的话,那么在使用的大多数浏览器支持XForms之前还需要几年时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.