如何在使用HTML表单时在HTTP请求正文中发送数据? [英] How to send data in the HTTP request body when using an HTML form?

查看:148
本文介绍了如何在使用HTML表单时在HTTP请求正文中发送数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTTP规范说明POST请求可以包含任意数据体。



HTML 表格元素可以POST到一个URL并且可能包含 input 元素,但是那些 input 元素会变成查询字符串。 / p>

如何获取一个 form 来发送HTTP POST请求正文中的数据它的提交按钮被按下了吗?

解决方案


包含任意数据。


没错。反过来,这些数据的格式有几种规格。在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.

这篇关于如何在使用HTML表单时在HTTP请求正文中发送数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆