且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在使用HTML表单时在HTTP请求正文中发送数据?

更新时间:2022-10-29 13:40:24


包含任意数据。


没错。反过来,这些数据的格式有几种规格。在HTML表单的情况下,最常用的是 application / x-www-form-urlencoded ,然后是 multipart / form-data 。您可以通过HTML < form> 元素的 enctype 属性来设置它。另见 17.13.4表单内容类型一章的HTML表单元素。





HTML表单元素可以POST到URL并可能包含输入元素,但这些输入元素会变成一个查询字符串。


确实如何 application / x-www-form-urlencoded 的作品。请注意,这个查询字符串实际上代表了整个HTTP请求体!所以请求主体绝对不是空的,因为你似乎认为。







如何获取表单以便在按下提交按钮时发送的HTTP POST请求正文中发送数据?


因此实际上已经这样做了。如果您有意发送表单本身的HTML DOM树形表示副本,如前面的声明中所暗示的那样,那么您可以通过JavaScript的一些帮助来实现该功能,如下所示:

 < form onsubmit =this.source.value = this.outerHTML> 
...
< input type =hiddenname =source/>
< input type =submit/>
< / form>

然后,表单的整个HTML DOM树表示形式将以字符串格式显示为请求参数,其名称为 source


The HTTP spec says that a POST request can contain an arbitrary body of data.

An HTML form element can POST to a URL and may contain input elements, but those input elements get turned into a query string.

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?

The HTTP spec says that a POST request can contain an arbitrary body of data.

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. You can set it via the enctype attribute of the HTML <form> element. See also chapter 17.13.4 Form Content Types of the HTML specification.


An HTML form element can POST to a URL and may contain input elements, but those input elements get turned into a query string.

That's indeed how application/x-www-form-urlencoded works. Do note that this query string actually represents the whole HTTP request body! 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?

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:

<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.