Request tag in html

Request

Интерфейс Request из Fetch API является запросом ресурсов или данных.

Создать новый объект Request можно, используя конструктор Request() (en-US), однако чаще всего встречается способ возврата объекта Request , как результат операции API. Например такой как service worker FetchEvent.request (en-US).

Конструктор

Создаёт новый Request объект.

Параметры

Содержит кешированное состояние запроса (напр., default , reload , no-cache ).

Содержит контекст запроса (напр., audio , image , iframe , и т.д..)

Содержит данные идентификации запроса (напр., «omit» , «same-origin» , «include» ). Значение по умолчанию: «same-origin» .

Возвращает строку из RequestDestination (en-US) enum, описывая назначение запроса. Это строка, указывающая тип запрошенных данных.

Содержит назначенный Headers (en-US) объект запроса (заголовки).

Содержит «subresource integrity (en-US) » значение запроса (напр., sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE= ).

Содержит метод запроса ( GET , POST , и т.д.)

Содержит режим запроса (напр., cors , no-cors , same-origin , navigate .)

Содержит режим перенаправления. Может быть одним из следующих: follow , error , или manual .

Содержит значение «referrer» («ссылающийся») запроса (например., client ).

Содержит политику «ссылающегося» данного запроса (e.g., no-referrer ).

Request имплементирует Body , таким образом наследуя следующие параметры:

Простой getter используемый для раскрытия ReadableStream (en-US) «тела» (body) содержимого.

Хранит Boolean (en-US), декларирующее использовалось ли «тело» ранее в ответе.

Методы

Создаёт копию текущего Request объекта.

Request имплементирует Body , таким образом наследуя следующие параметры:

Возвращает промис, который выполняется, возвращая ArrayBuffer репрезентацию тела запроса.

Возвращает promise который разрешается с помощью FormData представления тела запроса.

Returns a promise that resolves with a JSON representation of the request body.

Читайте также:  Python kivy черный экран

Returns a promise that resolves with an USVString (text) representation of the request body.

Примечание: The Body functions can be run only once; subsequent calls will resolve with empty strings/ArrayBuffers.

Examples

In the following snippet, we create a new request using the Request() constructor (for an image file in the same directory as the script), then return some property values of the request:

const request = new Request('https://www.mozilla.org/favicon.ico'); const URL = request.url; const method = request.method; const credentials = request.credentials; 

You could then fetch this request by passing the Request object in as a parameter to a WindowOrWorkerGlobalScope.fetch() call, for example:

fetch(request) .then(response => response.blob()) .then(blob =>  image.src = URL.createObjectURL(blob); >); 

In the following snippet, we create a new request using the Request() constructor with some initial data and body content for an api request which need a body payload:

const request = new Request('https://example.com', method: 'POST', body: ''>); const URL = request.url; const method = request.method; const credentials = request.credentials; const bodyUsed = request.bodyUsed; 

Примечание: Типом тела может быть только Blob , BufferSource , FormData , URLSearchParams , USVString или ReadableStream (en-US) поэтому, для добавления объекта JSON в полезную нагрузку вам необходимо структурировать этот объект.

Вы можете получить этот запрос API, передав объект Request в качестве параметра для вызова WindowOrWorkerGlobalScope.fetch() , например, и получить ответ:

fetch(request) .then(response =>  if (response.status === 200)  return response.json(); > else  throw new Error('Что-то пошло не так на API сервере.'); > >) .then(response =>  console.debug(response); // . >).catch(error =>  console.error(error); >); 

Specifications

Browser compatibility

BCD tables only load in the browser

Читай также

Found a content problem with this page?

This page was last modified on 7 нояб. 2022 г. 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.

Источник

Request tag in html

Two usage examples of the a tag in html post request

1. Use ajax to initiate a POST request
The HTML code is as follows:

a href="https://www.cnblogs.com/" class="a_post">Initiate a POST requesta>

The JQuery code is as follows:

$(".a_post").on("click",function(event)< event.preventDefault();//Invalidate the method that comes with a, that is, it cannot be adjusted to the URL in href (https://www.cnblogs.com/) $.ajax(< type: "POST", url: "url address", contentType:"application/json", data: JSON.stringify(),//parameter list dataType:"json", success: function(result) //Action after request is correct >, error: function(result) //What to do after the request fails > >); >);
2. Use the form to initiate a POST request
form id="_form" method="post" action="target"> input type="hidden" name="name" value="value" /> a onclick="document.getElementById('_form').submit();">Click submita> form>

Источник

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