Response
Baseline
Widely available
*
This feature is well established and works across many devices and browser versions. It’s been available across browsers since март 2017 г..
* Some parts of this feature may have varying levels of support.
Интерфейс Response из Fetch API представляет собой ответ на запрос.
Вы можете создать новый экземпляр объекта Response используя конструктор Response.Response(), но скорее всего вы столкнётесь с объектом Response, как результат какой-нибудь API операции — например, service worker Fetchevent.respondWith, или fetch().
Конструктор
Response()-
Создаёт новый экземпляр объекта
Response.
Свойства
Response.headersТолько для чтения-
Объект
Headers, который описывает заголовок ответа. Response.okТолько для чтения-
Булевское значение, которое указывает, выполнился ли запрос успешно или нет (то есть находится ли код ответа в диапазоне
200–299). Response.redirectedТолько для чтения-
Указывает, является ли результат запроса перенаправлением.
Response.statusТолько для чтения-
Код ответа.
Response.statusTextТолько для чтения-
Строка, соответствующая коду ответа (например,
OKдля кода200). Response.trailers-
A
Promiseresolving to aHeadersobject, associated with the response withResponse.headersfor values of the HTTPTrailerheader. Response.typeТолько для чтения-
The type of the response (e.g.,
basic,cors). Response.urlТолько для чтения-
The URL of the response.
Response.useFinalURL-
A boolean indicating whether this is the final URL of the response.
Body Interface Properties
Response implements Body, so it also has the following properties available to it:
Body.bodyТолько для чтения-
A simple getter exposing a
ReadableStreamof the body contents. Body.bodyUsedТолько для чтения-
Stores a
Booleanthat declares whether the body has been used in a response yet.
Методы
Response.clone()-
Creates a clone of a
Responseobject. Response.error()-
Returns a new
Responseobject associated with a network error. Response.redirect()-
Creates a new response with a different URL.
Body Interface Methods
Response implements Body, so it also has the following methods available to it:
Body.arrayBuffer()-
Takes a
Responsestream and reads it to completion. It returns a promise that resolves with anArrayBuffer. Body.blob()-
Takes a
Responsestream and reads it to completion. It returns a promise that resolves with aBlob. Body.formData()-
Takes a
Responsestream and reads it to completion. It returns a promise that resolves with aFormDataobject. Body.json()-
Takes a
Responsestream and reads it to completion. It returns a promise that resolves with the result of parsing the body text asJSON, which is a JavaScript value of datatype object, string, etc. Body.text()-
Takes a
Responsestream and reads it to completion. It returns a promise that resolves with aUSVString(text).
Примеры
>Fetching an image
In our basic fetch example (run example live) we use a simple fetch() call to grab an image and display it in an <img> element. The fetch() call returns a promise, which resolves to the Response object associated with the resource fetch operation.
You'll notice that since we are requesting an image, we need to run Body.blob (Response implements Body) to give the response its correct MIME type.
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;
});
You can also use the Response.Response() constructor to create your own custom Response object:
const response = new Response();
Ajax запрос
Здесь мы с помощью функции doAjax вызываем PHP скрипт, который генерирует JSON строку, и возвращает распарсенный JSON в виде JavaScript объекта. Также реализована простая обработка ошибок.
// Функция, которая делает 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);
Спецификации
| Specification |
|---|
| Fetch> # response-class> |
Совместимость с браузерами
Loading…