diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
commit | 074785cea106179cb3305637055ab0a009ca74f2 (patch) | |
tree | e6ae371cccd642aa2b67f39752a2cdf1fd4eb040 /files/ru/web/api/response | |
parent | da78a9e329e272dedb2400b79a3bdeebff387d47 (diff) | |
download | translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.gz translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.bz2 translated-content-074785cea106179cb3305637055ab0a009ca74f2.zip |
initial commit
Diffstat (limited to 'files/ru/web/api/response')
-rw-r--r-- | files/ru/web/api/response/index.html | 159 | ||||
-rw-r--r-- | files/ru/web/api/response/response/index.html | 81 |
2 files changed, 240 insertions, 0 deletions
diff --git a/files/ru/web/api/response/index.html b/files/ru/web/api/response/index.html new file mode 100644 index 0000000000..25726a3f0a --- /dev/null +++ b/files/ru/web/api/response/index.html @@ -0,0 +1,159 @@ +--- +title: Response +slug: Web/API/Response +tags: + - API + - Fetch + - Fetch API + - Interface + - Reference + - Response +translation_of: Web/API/Response +--- +<div>{{APIRef("Fetch API")}}</div> + +<p><span class="seoSummary">Интерфейс <strong><code>Response</code></strong> из <a href="/en-US/docs/Web/API/Fetch_API">Fetch API</a> представляет собой ответ на запрос.</span></p> + +<p>Вы можете создать новый экземпляр объекта <code>Response</code> используя конструктор {{domxref("Response.Response()")}}, но скорее всего вы столкнетесь с объектом <code>Response</code>, как результат какой-нибудь API операции — например, service worker {{domxref("Fetchevent.respondWith")}}, или {{domxref("WindowOrWorkerGlobalScope.fetch()")}}.</p> + +<h2 id="Конструктор">Конструктор</h2> + +<dl> + <dt>{{domxref("Response.Response","Response()")}}</dt> + <dd>Создаёт новый экземпляр объекта <code>Response</code>.</dd> +</dl> + +<h2 id="Свойства">Свойства</h2> + +<dl> + <dt>{{domxref("Response.headers")}} {{readonlyinline}}</dt> + <dd>Объект {{domxref("Headers")}}, который описывает заголовок ответа.</dd> + <dt>{{domxref("Response.ok")}} {{readonlyinline}}</dt> + <dd>Булевское значение, которое указывает, выполнился ли запрос успешно или нет (то есть находится ли код ответа в диапозоне <code>200</code>–<code>299</code>).</dd> + <dt>{{domxref("Response.redirected")}} {{ReadOnlyInline}}</dt> + <dd>Указывает, является ли результат запроса перенаправлением.</dd> + <dt>{{domxref("Response.status")}} {{readonlyinline}}</dt> + <dd>Код ответа.</dd> + <dt>{{domxref("Response.statusText")}} {{readonlyinline}}</dt> + <dd>Строка, соответствующая коду ответа (например, <code>OK</code> для кода <code>200</code>).</dd> + <dt>{{domxref("Response.trailers")}}</dt> + <dd>A {{domxref("Promise")}} resolving to a {{domxref("Headers")}} object, associated with the response with {{domxref("Response.headers")}} for values of the HTTP {{HTTPHeader("Trailer")}} header.</dd> + <dt>{{domxref("Response.type")}} {{readonlyinline}}</dt> + <dd>The type of the response (e.g., <code>basic</code>, <code>cors</code>).</dd> + <dt>{{domxref("Response.url")}} {{readonlyinline}}</dt> + <dd>The URL of the response.</dd> + <dt>{{domxref("Response.useFinalURL")}}</dt> + <dd>A boolean indicating whether this is the final URL of the response.</dd> +</dl> + +<h3 id="Body_Interface_Properties">Body Interface Properties</h3> + +<p><code>Response</code> implements {{domxref("Body")}}, so it also has the following properties available to it:</p> + +<dl> + <dt>{{domxref("Body.body")}} {{readonlyInline}}</dt> + <dd>A simple getter exposing a {{domxref("ReadableStream")}} of the body contents.</dd> + <dt>{{domxref("Body.bodyUsed")}} {{readonlyInline}}</dt> + <dd>Stores a {{domxref("Boolean")}} that declares whether the body has been used in a response yet.</dd> +</dl> + +<h2 id="Методы">Методы</h2> + +<dl> + <dt>{{domxref("Response.clone()")}}</dt> + <dd>Creates a clone of a <code>Response</code> object.</dd> + <dt>{{domxref("Response.error()")}}</dt> + <dd>Returns a new <code>Response</code> object associated with a network error.</dd> + <dt>{{domxref("Response.redirect()")}}</dt> + <dd>Creates a new response with a different URL.</dd> +</dl> + +<h3 id="Body_Interface_Methods">Body Interface Methods</h3> + +<p><code>Response</code> implements {{domxref("Body")}}, so it also has the following methods available to it:</p> + +<dl> + <dt>{{domxref("Body.arrayBuffer()")}}</dt> + <dd>Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{domxref("ArrayBuffer")}}.</dd> + <dt>{{domxref("Body.blob()")}}</dt> + <dd>Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("Blob")}}.</dd> + <dt>{{domxref("Body.formData()")}}</dt> + <dd>Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("FormData")}} object.</dd> + <dt>{{domxref("Body.json()")}}</dt> + <dd>Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as {{jsxref("JSON")}}, which is a JavaScript value of datatype object, string, etc.</dd> + <dt>{{domxref("Body.text()")}}</dt> + <dd>Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("USVString")}} (text).</dd> +</dl> + +<h2 id="Примеры">Примеры</h2> + +<h3 id="Fetching_an_image">Fetching an image</h3> + +<p>In our <a href="https://github.com/mdn/fetch-examples/tree/master/basic-fetch">basic fetch example</a> (<a href="http://mdn.github.io/fetch-examples/basic-fetch/">run example live</a>) we use a simple <code>fetch()</code> call to grab an image and display it in an {{htmlelement("img")}} element. The <code>fetch()</code> call returns a promise, which resolves to the <code>Response</code> object associated with the resource fetch operation.</p> + +<p>You'll notice that since we are requesting an image, we need to run {{domxref("Body.blob")}} ({{domxref("Response")}} implements Body) to give the response its correct MIME type.</p> + +<pre class="brush: js notranslate">const image = document.querySelector('.my-image'); +fetch('flowers.jpg').then(function(response) { + return response.blob(); +}).then(function(blob) { + const objectURL = URL.createObjectURL(blob); + image.src = objectURL; +});</pre> + +<p>You can also use the {{domxref("Response.Response()")}} constructor to create your own custom <code>Response</code> object:</p> + +<pre class="brush: js notranslate">const response = new Response();</pre> + +<h3 id="Ajax_запрос">Ajax запрос</h3> + +<p>Здесь мы с помощью функции doAjax вызываем PHP скрипт, который генерирует JSON строку, и возвращает распарсенный JSON в виде JavaScript объекта. Также реализована простая обработка ошибок.</p> + +<pre class="brush: js notranslate">// Функция, которая делает Ajax запрос +const doAjax = async () => { + const response = await fetch('Ajax.php'); // Генерируем объект Response + if (response.ok) { + const jVal = await response.json(); // Парсим тело ответа + return Promise.resolve(jVal); + } + else + return Promise.reject('*** PHP file not found'); + } +} + +// Вызываем doAjax и выводим результат в консоль +doAjax().then(console.log).catch(console.log); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Fetch','#response-class','Response')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.Response")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a></li> + <li><a href="/en-US/docs/Web/HTTP/Access_control_CORS">HTTP access control (CORS)</a></li> + <li><a href="/en-US/docs/Web/HTTP">HTTP</a></li> +</ul> diff --git a/files/ru/web/api/response/response/index.html b/files/ru/web/api/response/response/index.html new file mode 100644 index 0000000000..6a6b37cfe1 --- /dev/null +++ b/files/ru/web/api/response/response/index.html @@ -0,0 +1,81 @@ +--- +title: Response() +slug: Web/API/Response/Response +tags: + - API + - Constructor + - Fetch + - Reference + - Response +translation_of: Web/API/Response/Response +--- +<div>{{APIRef("Fetch")}}</div> + +<p>Конструктор <code><strong>Response()</strong></code> создаёт новый объект {{domxref("Response")}}.</p> + +<h2 id="Синтаксис">Синтаксис</h2> + +<pre class="syntaxbox notranslate">var <var>myResponse</var> = new Response(<var>body</var>, <var>init</var>);</pre> + +<h3 id="Параметры">Параметры</h3> + +<dl> + <dt><em>body</em> {{optional_inline}}</dt> + <dd>Объект, который определяет тело запроса. Может быть <code>null</code> (является значением по-умолчанию), или: + <ul> + <li>{{domxref("Blob")}}</li> + <li>{{domxref("BufferSource")}}</li> + <li>{{domxref("FormData")}}</li> + <li>{{domxref("ReadableStream")}}</li> + <li>{{domxref("URLSearchParams")}}</li> + <li>{{domxref("USVString")}}</li> + </ul> + </dd> + <dt><em>init</em> {{optional_inline}}</dt> + <dd>An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are: + <ul> + <li><code>status</code>: The status code for the reponse, e.g., <code>200</code>.</li> + <li><code>statusText</code>: The status message associated with the status code, e.g., <code>OK</code>.</li> + <li><code>headers</code>: Any headers you want to add to your response, contained within a {{domxref("Headers")}} object or object literal of {{domxref("ByteString")}} key/value pairs (see <a href="/en-US/docs/Web/HTTP/Headers">HTTP headers</a> for a reference).</li> + </ul> + </dd> +</dl> + +<h2 id="Примеры">Примеры</h2> + +<p>In our <a href="https://github.com/mdn/fetch-examples/tree/master/fetch-response">Fetch Response example</a> (see <a href="http://mdn.github.io/fetch-examples/fetch-response/">Fetch Response live</a>) we create a new <code>Response</code> object using the constructor, passing it a new {{domxref("Blob")}} as a body, and an init object containing a custom <code>status</code> and <code>statusText</code>:</p> + +<pre class="brush: js notranslate">var myBlob = new Blob(); +var init = { "status" : 200 , "statusText" : "SuperSmashingGreat!" }; +var myResponse = new Response(myBlob,init);</pre> + +<h2 id="Спецификации">Спецификации</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Fetch','#dom-response','Response()')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Совместимость_в_браузерах">Совместимость в браузерах</h2> + + + +<p>{{Compat("api.Response.Response")}}</p> + +<h2 id="Читай_также">Читай также</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a></li> + <li><a href="/en-US/docs/Web/HTTP/Access_control_CORS">HTTP access control (CORS)</a></li> + <li><a href="/en-US/docs/Web/HTTP">HTTP</a></li> +</ul> |