HTTP 规范规定 POST 请求可以包含任意数据体。
HTML form
元素可以 POST 到 URL 并且可能包含 input
元素,但是那些 input
元素会变成查询字符串。
如何让 form
在按下提交按钮时发送 HTTP POST 请求的主体中的数据?
最佳答案
The HTTP spec says that a POST request can contain an arbitrary body of data.
没错。然而,该数据的格式又有几种规范。对于 HTML 表单,最常用的是 application/x-www-form-urlencoded
, 其次是 multipart/form-data
.您可以通过 enctype
设置它HTML 的属性 <form>
元素。另见章节 17.13.4 Form Content Types 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.
确实是这样application/x-www-form-urlencoded
作品。请注意,这个查询字符串实际上代表了整个 HTTP 请求体!所以请求体绝对不是你想象的那样是空的。
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?
因此它实际上已经做到了。如果您打算发送表单本身的 HTML DOM 树表示的副本,如前面的语句中有所暗示,那么您可以借助 JavaScript 的一点帮助来实现,如下所示:
<form onsubmit="this.source.value=this.outerHTML">
...
<input type="hidden" name="source" />
<input type="submit" />
</form>
然后,表单的整个 HTML DOM 树表示形式为字符串格式,可作为名称为 source
的请求参数使用。 .
关于html - 使用 HTML 表单时如何在 HTTP 请求正文中发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2971112/