Http html form content type

Отправка форм — Протокол HTTP

В этом уроке мы рассмотрим особенности отправки форм в HTTP. Формы — это элементы HTML, которые применяются для сбора информации от посетителей веб-сайта. К ним относятся текстовые поля для ввода данных с клавиатуры, списки для выбора предопределенных данных, флажки для установки параметров. Работать будем с локально поднятым сервером, так как со сторонними серверами при тестировании на них наших уроков возникают сложности. В принципе, вы можете поэкспериментировать на любом доступном сервере. Только убедитесь, что он работает по HTTP, а не по HTTPS, так как там взаимодействие происходит немного по-другому и одного telnet будет недостаточно.

При отправке формы мы отправляем какие-то данные. Так как в HTTP не предусмотрены специальные места для отправки данных из форм, они отправляются в теле запроса. При этом в зависимости от того, какой заголовок Content-Type установлен, интерпретируется то, как будут закодированы данные при отправке. Обычно используется следующий формат Content-Type: application/x-www-form-urlencoded. Это простой формат — ключ равно значение и амперсанд между ними.

login=smith&password=12345678 

Таким нехитрым способом мы можем продолжать строку, передавая столько данных, сколько захотим. Теперь попробуем сделать запрос к нашему локальному серверу.

login=smith&password=12345678 # отправляем данные HTTP/1.1 200 OK X-Powered-By: Express Connection: close Content-Type: text/html; charset=utf-8 Content-Length: 7 ETag: W/"c-r0WEeVxJ7IpMIG20rN7HX9ndB4c" Date: Thu, 09 Jul 2020 03:32:54 GMT Done! Connection closed by foreign host. 

После отправки сервер, получив те 29 символов, которые мы указали в Content-Length, сразу отправляет нам ответ HTTP/1.1 200 OK, в body которого одно слово Done! . Как видим, в ответе также присутствует Content-Length равный 7 .

Читайте также:  Ece4co vis ne jp shock wave8 tamaneco html

Есть еще несколько особенностей, которые нужно знать, когда мы работаем с формами в HTTP. Первая из них связана с кодированием. Поскольку это текстовый формат, то в нем очень легко допустить различные неоднозначности. Предположим в пароле используется знак = .

login=smith&password=1234=5678 

Каким образом правильно распарсить этот результат? Не исключено, что сервер поймет то, что мы отправляем, так как парсинг происходит слева направо, но это ничем не гарантированно. Более того, в названии поля также могут быть специальные символы. Поэтому все, что отправляется на сервер, должно быть закодировано. Обычно кодированием занимаются браузеры. Но в целом, если вы пишете какие-то скрипты и используемые библиотеки об этом не заботятся, это должны сделать вы. Закодированный символ = выглядит так — %3D и не важно, какой это запрос: POST или GET. Такие закодированные последовательности символов вы можете часто видеть в адресной строке браузера. body с закодированным = приводится в примере ниже:

login=smith&password=1234%3D5678 

Еще одна особенность связана с тем, что иногда нам нужно отправить данные, вложенные друг в друга. Например, массив опций. В таком случае тело может выглядеть так:

=smith&user[password]=12345678 

Нюанс в том, что HTTP не умеет работать с такими данными. Их обработкой занимаются мидлвары (англ. middlewares — промежуточное программное обеспечение). Но если вы, например, пишете свою собственную реализацию сервера, вам придется парсить такие данные самостоятельно.

Другие способы кодирования

Помимо обычного кодирования ключ=значение существуют и другие форматы, но самым популярным является формат JSON. У него достаточно много преимуществ, в числе которых:

  • JSON представляет собой строку, что и необходимо при передаче данных по сети
  • Не зависит от языка
  • С его помощью можно описывать сложные иерархические структуры
  • Легко читается человеком

В данный момент он считается стандартом для обмена информацией между сервисами в интернете. Строка JSON выглядит следующим образом:

 "firstName": "John", "lastName": "Smith", "children": [  "firstName": "Max", "lastName": "Smith" >,  "firstName": "Annie", "lastName": "Smith" > ] > 

Открыть доступ

Курсы программирования для новичков и опытных разработчиков. Начните обучение бесплатно

  • 130 курсов, 2000+ часов теории
  • 1000 практических заданий в браузере
  • 360 000 студентов

Наши выпускники работают в компаниях:

Источник

Content-Type

The Content-Type representation header is used to indicate the original media type of the resource (prior to any content encoding applied for sending).

In responses, a Content-Type header provides the client with the actual content type of the returned content. This header’s value may be ignored, for example when browsers perform MIME sniffing; set the X-Content-Type-Options header value to nosniff to prevent this behavior.

In requests, (such as POST or PUT ), the client tells the server what type of data is actually sent.

Header type Representation header
Forbidden header name no
CORS-safelisted response header yes
CORS-safelisted request header yes, with the additional restriction that values can’t contain a CORS-unsafe request header byte: 0x00-0x1F (except 0x09 (HT)), «():<>?@[\]<> , and 0x7F (DEL).
It also needs to have a MIME type of its parsed value (ignoring parameters) of either application/x-www-form-urlencoded , multipart/form-data , or text/plain .

Syntax

Content-Type: text/html; charset=utf-8 Content-Type: multipart/form-data; boundary=something 

Directives

The MIME type of the resource or the data.

The character encoding standard. Case insensitive, lowercase is preferred.

For multipart entities the boundary directive is required. The directive consists of 1 to 70 characters from a set of characters (and not ending with white space) known to be very robust through email gateways. It is used to encapsulate the boundaries of the multiple parts of the message. Often, the header boundary is prepended with two dashes and the final boundary has two dashes appended at the end.

Examples

Content-Type in HTML forms

In a POST request, resulting from an HTML form submission, the Content-Type of the request is specified by the enctype attribute on the element.

form action="/" method="post" enctype="multipart/form-data"> input type="text" name="description" value="some text" /> input type="file" name="myFile" /> button type="submit">Submitbutton> form> 

The request looks something like this (less interesting headers are omitted here):

POST /foo HTTP/1.1 Content-Length: 68137 Content-Type: multipart/form-data; boundary=---------------------------974767299852498929531610575 -----------------------------974767299852498929531610575 Content-Disposition: form-data; name="description" some text -----------------------------974767299852498929531610575 Content-Disposition: form-data; name="myFile"; filename="foo.txt" Content-Type: text/plain (content of the uploaded file foo.txt) -----------------------------974767299852498929531610575-- 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 10, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

: The Form element

The HTML element represents a document section containing interactive controls for submitting information.

Try it

It is possible to use the :valid and :invalid CSS pseudo-classes to style a element based on whether the elements inside the form are valid.

Attributes

This element includes the global attributes.

Comma-separated content types the server accepts.

Note: This attribute has been deprecated and should not be used. Instead, use the accept attribute on elements.

Space-separated character encodings the server accepts. The browser uses them in the order in which they are listed. The default value means the same encoding as the page. (In previous versions of HTML, character encodings could also be delimited by commas.)

A nonstandard attribute used by iOS Safari that controls how textual form elements should be automatically capitalized. autocapitalize attributes on a form elements override it on . Possible values:

  • none : No automatic capitalization.
  • sentences (default): Capitalize the first letter of each sentence.
  • words : Capitalize the first letter of each word.
  • characters : Capitalize all characters — that is, uppercase.

Indicates whether input elements can by default have their values automatically completed by the browser. autocomplete attributes on form elements override it on . Possible values:

  • off : The browser may not automatically complete entries. (Browsers tend to ignore this for suspected login forms; see The autocomplete attribute and login fields.)
  • on : The browser may automatically complete entries.

The name of the form. The value must not be the empty string, and must be unique among the form elements in the forms collection that it is in, if any.

Controls the annotations and what kinds of links the form creates. Annotations include external , nofollow , opener , noopener , and noreferrer . Link types include help , prev , next , search , and license . The rel value is a space-separated list of these enumerated values.

Attributes for form submission

The following attributes control behavior during form submission.

The URL that processes the form submission. This value can be overridden by a formaction attribute on a , , or element. This attribute is ignored when method=»dialog» is set.

If the value of the method attribute is post , enctype is the MIME type of the form submission. Possible values:

  • application/x-www-form-urlencoded : The default value.
  • multipart/form-data : Use this if the form contains elements with type=file .
  • text/plain : Useful for debugging purposes.

This value can be overridden by formenctype attributes on , , or elements.

The HTTP method to submit the form with. The only allowed methods/values are (case insensitive):

  • post : The POST method; form data sent as the request body.
  • get (default): The GET ; form data appended to the action URL with a ? separator. Use this method when the form has no side effects.
  • dialog : When the form is inside a , closes the dialog and causes a submit event to be fired on submission, without submitting data or clearing the form.

This value is overridden by formmethod attributes on , , or elements.

This Boolean attribute indicates that the form shouldn’t be validated when submitted. If this attribute is not set (and therefore the form is validated), it can be overridden by a formnovalidate attribute on a , , or element belonging to the form.

Indicates where to display the response after submitting the form. It is a name/keyword for a browsing context (for example, tab, window, or iframe). The following keywords have special meanings:

  • _self (default): Load into the same browsing context as the current one.
  • _blank : Load into a new unnamed browsing context. This provides the same behavior as setting rel=»noopener» which does not set window.opener .
  • _parent : Load into the parent browsing context of the current one. If no parent, behaves the same as _self .
  • _top : Load into the top-level browsing context (i.e., the browsing context that is an ancestor of the current one and has no parent). If no parent, behaves the same as _self .

This value can be overridden by a formtarget attribute on a , , or element.

Examples

form method="get"> label> Name: input name="submitted-name" autocomplete="name" /> label> button>Savebutton> form> form method="post"> label> Name: input name="submitted-name" autocomplete="name" /> label> button>Savebutton> form> form method="post"> fieldset> legend>Do you agree to the terms?legend> label>input type="radio" name="radio" value="yes" /> Yeslabel> label>input type="radio" name="radio" value="no" /> Nolabel> fieldset> form> 

Result

Technical summary

Content categories Flow content, palpable content
Permitted content Flow content, but not containing elements
Tag omission None, both the starting and ending tag are mandatory.
Permitted parents Any element that accepts flow content
Implicit ARIA role form if the form has an accessible name, otherwise no corresponding role
Permitted ARIA roles search , none or presentation
DOM interface HTMLFormElement

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 13, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Оцените статью