Форма отправки запроса html

: 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.
Читайте также:  Python pickle utf 8

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.

Источник

Отправка данных формы

Сама форма обычно предназначена для получения от пользователя информации для дальнейшей пересылки её на сервер, где данные формы принимает программа-обработчик. Такая программа может быть написана на любом серверном языке программирования вроде PHP, Perl и др. Адрес программы указывается в атрибуте action тега , как показано в примере 1.

Пример 1. Отправка данных формы

В этом примере данные формы, обозначенные атрибутом name ( login и password ), будут переданы в файл по адресу /example/handler.php. Если атрибут action не указывать, то передача происходит на адрес текущей страницы.

Передача на сервер происходит двумя разными методами: GET и POST, для задания метода в теге используется атрибут method , а его значениями выступают ключевые слова get и post . Если атрибут method не задан, то по умолчанию данные отправляются на сервер методом GET. В табл. 1 показаны различия между этими методами.

Табл. 1. Различия между методами GET и POST

GET POST
Ограничение на объём4 КбОграничения задаются сервером.
Передаваемые данныеВидны сразу всем.Видны только при просмотре через расширения браузера или другими методами.
КэшированиеСтраницы с разными запросами считаются различными, их можно кэшировать как отдельные документы.Страница всегда одна.
ЗакладкиСтраницу с запросом можно добавить в закладки браузера и обратиться к ней позже.Страницы с разными запросами имеют один адрес, запрос повторить нельзя.

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

Уникальное сочетание параметров в адресной строке однозначно идентифицирует страницу, так что страницы с адресами ?q=node/add и ?q=node считаются разными. Эту особенность используют системы управления контентом (CMS, Content management system) для создания множества страниц сайта. В реальности же используется один файл, который получает запрос GET и согласно ему формирует содержимое документа.

Ниже перечислены типовые области применения этих методов на сайтах.

GET

Передача небольших текстовых данных на сервер; поиск по сайту.

Поисковые системы, формы поиска по сайту всегда отправляются методом GET, это позволяет делиться результатами поиска с друзьями, слать ссылку по почте или выкладывать её на форуме.

POST

Пересылка файлов (фотографий, архивов, программ и др.); отправка комментариев; добавление и редактирование сообщений на форуме, блоге.

Работа с формой по умолчанию происходит в текущей вкладке браузера, при этом допустимо при отправке формы изменить этот параметр и открывать обработчик формы в новой вкладке или во фрейме. Такое поведение задаётся через «имя контекста», которое выступает значением атрибута target тега . Популярные значения это _blank для открытия формы в новом окне или вкладке, и имя фрейма, которое задаётся атрибутом name тега (пример 2).

Пример 2. Открытие формы во фрейме

В данном примере при нажатии на кнопку «Отправить» результат отправки формы открывается во фрейме с именем area .

Элементы формы традиционно располагаются внутри тега , тем самым определяя те данные, которые будут передаваться на сервер. В то же время в HTML5 есть возможность отделить форму от её элементов. Это сделано для удобства и универсальности, так, сложный макет может содержать несколько форм, которые не должны пересекаться меж собой или к примеру, некоторые элементы выводятся с помощью скриптов в одном месте страницы, а сама форма находится в другом. Связь между формой и её элементами происходит в таком случае через идентификатор формы, а к элементам следует добавить атрибут form со значением, равным этому идентификатору (пример 3).

Пример 3. Связывание формы с полями

В этом примере тег однозначно отождествляется через идентификатор auth , а к полям, которые следует отправить с помощью формы, добавляется form=»auth» . При этом поведение элементов не меняется, при нажатии на кнопку логин и пароль пересылаются на обработчик handler.php.

Хотя параметры передачи формы традиционно указываются в теге , их можно перенести и в кнопки отправки формы ( и ). Для этого применяется набор атрибутов formaction , formmethod , formenctype и formtarget , которые являются аналогами соответствующих атрибутов без приставки form. В примере 4 показано использование этих атрибутов.

Все новые атрибуты форм не поддерживаются некоторыми браузерами, в частности, Internet Explorer и Safari.

Источник

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