From b0a393384aa4021c915e6a650c75ff328a054cb2 Mon Sep 17 00:00:00 2001 From: MDN Date: Thu, 1 Jul 2021 00:37:12 +0000 Subject: [CRON] sync translated content --- files/de/_redirects.txt | 8 ++ files/de/_wikihistory.json | 96 +++++++------- .../orphaned/web/api/body/arraybuffer/index.html | 88 +++++++++++++ files/de/orphaned/web/api/body/blob/index.html | 74 +++++++++++ files/de/orphaned/web/api/body/body/index.html | 87 +++++++++++++ files/de/orphaned/web/api/body/bodyused/index.html | 74 +++++++++++ files/de/orphaned/web/api/body/formdata/index.html | 63 +++++++++ files/de/orphaned/web/api/body/index.html | 100 ++++++++++++++ files/de/orphaned/web/api/body/json/index.html | 74 +++++++++++ files/de/orphaned/web/api/body/text/index.html | 81 ++++++++++++ files/de/web/api/body/arraybuffer/index.html | 87 ------------- files/de/web/api/body/blob/index.html | 73 ----------- files/de/web/api/body/body/index.html | 86 ------------- files/de/web/api/body/bodyused/index.html | 73 ----------- files/de/web/api/body/formdata/index.html | 62 --------- files/de/web/api/body/index.html | 99 -------------- files/de/web/api/body/json/index.html | 73 ----------- files/de/web/api/body/text/index.html | 80 ------------ files/es/_redirects.txt | 3 + files/es/_wikihistory.json | 38 +++--- files/es/orphaned/web/api/body/formdata/index.html | 73 +++++++++++ files/es/orphaned/web/api/body/index.html | 100 ++++++++++++++ files/es/orphaned/web/api/body/json/index.html | 83 ++++++++++++ files/es/web/api/body/formdata/index.html | 72 ----------- files/es/web/api/body/index.html | 99 -------------- files/es/web/api/body/json/index.html | 82 ------------ files/fr/_redirects.txt | 2 + files/fr/_wikihistory.json | 40 +++--- files/fr/orphaned/web/api/body/index.html | 97 ++++++++++++++ files/fr/orphaned/web/api/body/json/index.html | 87 +++++++++++++ files/fr/web/api/body/index.html | 96 -------------- files/fr/web/api/body/json/index.html | 86 ------------- files/ja/_redirects.txt | 8 ++ files/ja/_wikihistory.json | 132 +++++++++---------- .../orphaned/web/api/body/arraybuffer/index.html | 109 ++++++++++++++++ files/ja/orphaned/web/api/body/blob/index.html | 80 ++++++++++++ files/ja/orphaned/web/api/body/body/index.html | 95 ++++++++++++++ files/ja/orphaned/web/api/body/bodyused/index.html | 82 ++++++++++++ files/ja/orphaned/web/api/body/formdata/index.html | 73 +++++++++++ files/ja/orphaned/web/api/body/index.html | 96 ++++++++++++++ files/ja/orphaned/web/api/body/json/index.html | 92 +++++++++++++ files/ja/orphaned/web/api/body/text/index.html | 89 +++++++++++++ files/ja/web/api/body/arraybuffer/index.html | 108 ---------------- files/ja/web/api/body/blob/index.html | 79 ------------ files/ja/web/api/body/body/index.html | 94 -------------- files/ja/web/api/body/bodyused/index.html | 81 ------------ files/ja/web/api/body/formdata/index.html | 72 ----------- files/ja/web/api/body/index.html | 95 -------------- files/ja/web/api/body/json/index.html | 91 ------------- files/ja/web/api/body/text/index.html | 88 ------------- files/ko/_redirects.txt | 2 + files/ko/_wikihistory.json | 26 ++-- files/ko/orphaned/web/api/body/index.html | 98 ++++++++++++++ files/ko/orphaned/web/api/body/json/index.html | 74 +++++++++++ files/ko/web/api/body/index.html | 97 -------------- files/ko/web/api/body/json/index.html | 73 ----------- files/pt-br/_redirects.txt | 2 + files/pt-br/_wikihistory.json | 24 ++-- files/pt-br/orphaned/web/api/body/index.html | 98 ++++++++++++++ files/pt-br/orphaned/web/api/body/json/index.html | 90 +++++++++++++ files/pt-br/web/api/body/index.html | 97 -------------- files/pt-br/web/api/body/json/index.html | 89 ------------- files/ru/_redirects.txt | 4 + files/ru/_wikihistory.json | 48 +++---- .../orphaned/web/api/body/arraybuffer/index.html | 91 +++++++++++++ files/ru/orphaned/web/api/body/formdata/index.html | 60 +++++++++ files/ru/orphaned/web/api/body/index.html | 100 ++++++++++++++ files/ru/orphaned/web/api/body/json/index.html | 75 +++++++++++ files/ru/web/api/body/arraybuffer/index.html | 90 ------------- files/ru/web/api/body/formdata/index.html | 59 --------- files/ru/web/api/body/index.html | 99 -------------- files/ru/web/api/body/json/index.html | 74 ----------- files/zh-cn/_redirects.txt | 8 ++ files/zh-cn/_wikihistory.json | 130 +++++++++---------- .../orphaned/web/api/body/arraybuffer/index.html | 143 +++++++++++++++++++++ files/zh-cn/orphaned/web/api/body/blob/index.html | 137 ++++++++++++++++++++ files/zh-cn/orphaned/web/api/body/body/index.html | 87 +++++++++++++ .../orphaned/web/api/body/bodyused/index.html | 135 +++++++++++++++++++ .../orphaned/web/api/body/formdata/index.html | 123 ++++++++++++++++++ files/zh-cn/orphaned/web/api/body/index.html | 97 ++++++++++++++ files/zh-cn/orphaned/web/api/body/json/index.html | 91 +++++++++++++ files/zh-cn/orphaned/web/api/body/text/index.html | 86 +++++++++++++ files/zh-cn/web/api/body/arraybuffer/index.html | 142 -------------------- files/zh-cn/web/api/body/blob/index.html | 136 -------------------- files/zh-cn/web/api/body/body/index.html | 86 ------------- files/zh-cn/web/api/body/bodyused/index.html | 134 ------------------- files/zh-cn/web/api/body/formdata/index.html | 122 ------------------ files/zh-cn/web/api/body/index.html | 96 -------------- files/zh-cn/web/api/body/json/index.html | 90 ------------- files/zh-cn/web/api/body/text/index.html | 85 ------------ files/zh-tw/_redirects.txt | 2 + files/zh-tw/_wikihistory.json | 26 ++-- files/zh-tw/orphaned/web/api/body/index.html | 100 ++++++++++++++ files/zh-tw/orphaned/web/api/body/json/index.html | 74 +++++++++++ files/zh-tw/web/api/body/index.html | 99 -------------- files/zh-tw/web/api/body/json/index.html | 73 ----------- 96 files changed, 3875 insertions(+), 3797 deletions(-) create mode 100644 files/de/orphaned/web/api/body/arraybuffer/index.html create mode 100644 files/de/orphaned/web/api/body/blob/index.html create mode 100644 files/de/orphaned/web/api/body/body/index.html create mode 100644 files/de/orphaned/web/api/body/bodyused/index.html create mode 100644 files/de/orphaned/web/api/body/formdata/index.html create mode 100644 files/de/orphaned/web/api/body/index.html create mode 100644 files/de/orphaned/web/api/body/json/index.html create mode 100644 files/de/orphaned/web/api/body/text/index.html delete mode 100644 files/de/web/api/body/arraybuffer/index.html delete mode 100644 files/de/web/api/body/blob/index.html delete mode 100644 files/de/web/api/body/body/index.html delete mode 100644 files/de/web/api/body/bodyused/index.html delete mode 100644 files/de/web/api/body/formdata/index.html delete mode 100644 files/de/web/api/body/index.html delete mode 100644 files/de/web/api/body/json/index.html delete mode 100644 files/de/web/api/body/text/index.html create mode 100644 files/es/orphaned/web/api/body/formdata/index.html create mode 100644 files/es/orphaned/web/api/body/index.html create mode 100644 files/es/orphaned/web/api/body/json/index.html delete mode 100644 files/es/web/api/body/formdata/index.html delete mode 100644 files/es/web/api/body/index.html delete mode 100644 files/es/web/api/body/json/index.html create mode 100644 files/fr/orphaned/web/api/body/index.html create mode 100644 files/fr/orphaned/web/api/body/json/index.html delete mode 100644 files/fr/web/api/body/index.html delete mode 100644 files/fr/web/api/body/json/index.html create mode 100644 files/ja/orphaned/web/api/body/arraybuffer/index.html create mode 100644 files/ja/orphaned/web/api/body/blob/index.html create mode 100644 files/ja/orphaned/web/api/body/body/index.html create mode 100644 files/ja/orphaned/web/api/body/bodyused/index.html create mode 100644 files/ja/orphaned/web/api/body/formdata/index.html create mode 100644 files/ja/orphaned/web/api/body/index.html create mode 100644 files/ja/orphaned/web/api/body/json/index.html create mode 100644 files/ja/orphaned/web/api/body/text/index.html delete mode 100644 files/ja/web/api/body/arraybuffer/index.html delete mode 100644 files/ja/web/api/body/blob/index.html delete mode 100644 files/ja/web/api/body/body/index.html delete mode 100644 files/ja/web/api/body/bodyused/index.html delete mode 100644 files/ja/web/api/body/formdata/index.html delete mode 100644 files/ja/web/api/body/index.html delete mode 100644 files/ja/web/api/body/json/index.html delete mode 100644 files/ja/web/api/body/text/index.html create mode 100644 files/ko/orphaned/web/api/body/index.html create mode 100644 files/ko/orphaned/web/api/body/json/index.html delete mode 100644 files/ko/web/api/body/index.html delete mode 100644 files/ko/web/api/body/json/index.html create mode 100644 files/pt-br/orphaned/web/api/body/index.html create mode 100644 files/pt-br/orphaned/web/api/body/json/index.html delete mode 100644 files/pt-br/web/api/body/index.html delete mode 100644 files/pt-br/web/api/body/json/index.html create mode 100644 files/ru/orphaned/web/api/body/arraybuffer/index.html create mode 100644 files/ru/orphaned/web/api/body/formdata/index.html create mode 100644 files/ru/orphaned/web/api/body/index.html create mode 100644 files/ru/orphaned/web/api/body/json/index.html delete mode 100644 files/ru/web/api/body/arraybuffer/index.html delete mode 100644 files/ru/web/api/body/formdata/index.html delete mode 100644 files/ru/web/api/body/index.html delete mode 100644 files/ru/web/api/body/json/index.html create mode 100644 files/zh-cn/orphaned/web/api/body/arraybuffer/index.html create mode 100644 files/zh-cn/orphaned/web/api/body/blob/index.html create mode 100644 files/zh-cn/orphaned/web/api/body/body/index.html create mode 100644 files/zh-cn/orphaned/web/api/body/bodyused/index.html create mode 100644 files/zh-cn/orphaned/web/api/body/formdata/index.html create mode 100644 files/zh-cn/orphaned/web/api/body/index.html create mode 100644 files/zh-cn/orphaned/web/api/body/json/index.html create mode 100644 files/zh-cn/orphaned/web/api/body/text/index.html delete mode 100644 files/zh-cn/web/api/body/arraybuffer/index.html delete mode 100644 files/zh-cn/web/api/body/blob/index.html delete mode 100644 files/zh-cn/web/api/body/body/index.html delete mode 100644 files/zh-cn/web/api/body/bodyused/index.html delete mode 100644 files/zh-cn/web/api/body/formdata/index.html delete mode 100644 files/zh-cn/web/api/body/index.html delete mode 100644 files/zh-cn/web/api/body/json/index.html delete mode 100644 files/zh-cn/web/api/body/text/index.html create mode 100644 files/zh-tw/orphaned/web/api/body/index.html create mode 100644 files/zh-tw/orphaned/web/api/body/json/index.html delete mode 100644 files/zh-tw/web/api/body/index.html delete mode 100644 files/zh-tw/web/api/body/json/index.html diff --git a/files/de/_redirects.txt b/files/de/_redirects.txt index fca382c6c5..d0d794c75e 100644 --- a/files/de/_redirects.txt +++ b/files/de/_redirects.txt @@ -483,6 +483,14 @@ /de/docs/Updating_web_applications_for_Firefox_3 /de/docs/Mozilla/Firefox/Releases/3/Updating_web_applications /de/docs/Verwenden_des_Cache_beim_Firefox_1.5 /de/docs/Mozilla/Firefox/Releases/1.5/Using_Firefox_1.5_caching /de/docs/Web/API/AudioContext/decodeAudioData /de/docs/Web/API/BaseAudioContext/decodeAudioData +/de/docs/Web/API/Body /de/docs/orphaned/Web/API/Body +/de/docs/Web/API/Body/arrayBuffer /de/docs/orphaned/Web/API/Body/arrayBuffer +/de/docs/Web/API/Body/blob /de/docs/orphaned/Web/API/Body/blob +/de/docs/Web/API/Body/body /de/docs/orphaned/Web/API/Body/body +/de/docs/Web/API/Body/bodyUsed /de/docs/orphaned/Web/API/Body/bodyUsed +/de/docs/Web/API/Body/formData /de/docs/orphaned/Web/API/Body/formData +/de/docs/Web/API/Body/json /de/docs/orphaned/Web/API/Body/json +/de/docs/Web/API/Body/text /de/docs/orphaned/Web/API/Body/text /de/docs/Web/API/CSSRule.cssText /de/docs/Web/API/CSSRule/cssText /de/docs/Web/API/ChildNode /de/docs/orphaned/Web/API/ChildNode /de/docs/Web/API/ChildNode/remove /de/docs/orphaned/Web/API/ChildNode/remove diff --git a/files/de/_wikihistory.json b/files/de/_wikihistory.json index 755d832c7b..52111561a4 100644 --- a/files/de/_wikihistory.json +++ b/files/de/_wikihistory.json @@ -2499,54 +2499,6 @@ "fscholz" ] }, - "Web/API/Body": { - "modified": "2020-10-15T22:15:22.404Z", - "contributors": [ - "fmeyertoens" - ] - }, - "Web/API/Body/arrayBuffer": { - "modified": "2020-10-15T22:15:22.326Z", - "contributors": [ - "SebinNyshkim" - ] - }, - "Web/API/Body/blob": { - "modified": "2020-10-15T22:15:22.311Z", - "contributors": [ - "SebinNyshkim" - ] - }, - "Web/API/Body/body": { - "modified": "2020-10-15T22:15:22.169Z", - "contributors": [ - "SebinNyshkim" - ] - }, - "Web/API/Body/bodyUsed": { - "modified": "2020-10-15T22:15:22.317Z", - "contributors": [ - "SebinNyshkim" - ] - }, - "Web/API/Body/formData": { - "modified": "2020-10-15T22:15:22.274Z", - "contributors": [ - "SebinNyshkim" - ] - }, - "Web/API/Body/json": { - "modified": "2020-10-15T22:15:23.782Z", - "contributors": [ - "SebinNyshkim" - ] - }, - "Web/API/Body/text": { - "modified": "2020-10-15T22:15:23.627Z", - "contributors": [ - "SebinNyshkim" - ] - }, "Web/API/CSS": { "modified": "2020-10-15T22:34:59.314Z", "contributors": [ @@ -14548,6 +14500,54 @@ "AARADEANCA" ] }, + "orphaned/Web/API/Body": { + "modified": "2020-10-15T22:15:22.404Z", + "contributors": [ + "fmeyertoens" + ] + }, + "orphaned/Web/API/Body/arrayBuffer": { + "modified": "2020-10-15T22:15:22.326Z", + "contributors": [ + "SebinNyshkim" + ] + }, + "orphaned/Web/API/Body/blob": { + "modified": "2020-10-15T22:15:22.311Z", + "contributors": [ + "SebinNyshkim" + ] + }, + "orphaned/Web/API/Body/body": { + "modified": "2020-10-15T22:15:22.169Z", + "contributors": [ + "SebinNyshkim" + ] + }, + "orphaned/Web/API/Body/bodyUsed": { + "modified": "2020-10-15T22:15:22.317Z", + "contributors": [ + "SebinNyshkim" + ] + }, + "orphaned/Web/API/Body/formData": { + "modified": "2020-10-15T22:15:22.274Z", + "contributors": [ + "SebinNyshkim" + ] + }, + "orphaned/Web/API/Body/json": { + "modified": "2020-10-15T22:15:23.782Z", + "contributors": [ + "SebinNyshkim" + ] + }, + "orphaned/Web/API/Body/text": { + "modified": "2020-10-15T22:15:23.627Z", + "contributors": [ + "SebinNyshkim" + ] + }, "orphaned/Web/API/ChildNode": { "modified": "2019-03-23T22:06:18.037Z", "contributors": [ diff --git a/files/de/orphaned/web/api/body/arraybuffer/index.html b/files/de/orphaned/web/api/body/arraybuffer/index.html new file mode 100644 index 0000000000..9e6cc2f090 --- /dev/null +++ b/files/de/orphaned/web/api/body/arraybuffer/index.html @@ -0,0 +1,88 @@ +--- +title: Body.arrayBuffer() +slug: orphaned/Web/API/Body/arrayBuffer +translation_of: Web/API/Body/arrayBuffer +original_slug: Web/API/Body/arrayBuffer +--- +
{{APIRef("Fetch")}}
+ +

Die Methode arrayBuffer() des {{domxref("Body")}} Mixin nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Sie gibt ein Promise zurück, welches in einen {{domxref("ArrayBuffer")}} aufgelöst wird.

+ +

Syntax

+ +
response.arrayBuffer().then(function(buffer) {
+  // mach etwas mit dem Buffer
+});
+ +

Parameter

+ +

Keine.

+ +

Rückgabewert

+ +

Ein Promise, welches in einen {{domxref("ArrayBuffer")}} aufgelöst wird.

+ +

Beispiel

+ +

In unserem Live-Beispiel zum Abruf eines Array Buffers haben wir einen Wiedergabe-Knopf. Bei einem Klick darauf wird die Funktion getData() ausgeführt. Beachten Sie, dass vor der Wiedergabe die ganze Audio-Datei heruntergeladen wird. Benötigen Sie eine Wiedergabe noch während des Downloads (Streaming) ziehen Sie {{domxref("HTMLAudioElement")}} in Betracht:

+ +
new Audio(music.ogg).play()
+
+ +

In getData() erstellen wir eine neue Anfrage mit dem {{domxref("Request.Request")}} Konstruktor, um dann einen OGG Musik-Track abzurufen. Wir benutzen ebenfalls {{domxref("AudioContext.createBufferSource")}} um eine Audio-Puffer-Quelle zu erstellen. Ist der Abruf erfolgreich, lesen wir mit arrayBuffer() einen {{domxref("ArrayBuffer")}} aus der Antwort, dekodieren die Audiodaten mit {{domxref("AudioContext.decodeAudioData")}}, setzen die dekodierten Daten als Quelle für den Audio-Puffer fest und verbinden die Quelle mit {{domxref("AudioContext.destination")}}.

+ +

Wenn getData() durchgelaufen ist, starten wir die Wiedergabe mit start(0) und deaktivieren den Wiedergabe-Knopf, damit er nicht erneut geklickt werden kann, während die Wiedergabe läuft (was zu einem Fehler führen würde).

+ +
function getData() {
+  source = audioCtx.createBufferSource();
+
+  var myRequest = new Request('viper.ogg');
+
+  fetch(myRequest).then(function(response) {
+    return response.arrayBuffer();
+  }).then(function(buffer) {
+    audioCtx.decodeAudioData(buffer, function(decodedData) {
+      source.buffer = decodedData;
+      source.connect(audioCtx.destination);
+    });
+  });
+};
+
+// Knöpfe zum Abspielen und Anhalten verknüpfen
+
+play.onclick = function() {
+  getData();
+  source.start(0);
+  play.setAttribute('disabled', 'disabled');
+}
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-arraybuffer','arrayBuffer()')}}{{Spec2('Fetch')}} 
+ +

Browserkompatibilität

+ + + +

{{Compat("api.Body.arrayBuffer")}}

+ +

Siehe auch

+ + diff --git a/files/de/orphaned/web/api/body/blob/index.html b/files/de/orphaned/web/api/body/blob/index.html new file mode 100644 index 0000000000..dc687a369e --- /dev/null +++ b/files/de/orphaned/web/api/body/blob/index.html @@ -0,0 +1,74 @@ +--- +title: Body.blob() +slug: orphaned/Web/API/Body/blob +translation_of: Web/API/Body/blob +original_slug: Web/API/Body/blob +--- +
{{APIRef("Fetch")}}
+ +

Die Methode blob() des {{domxref("Body")}} Mixin nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Sie gibt ein Promise zurück, welches in einen {{domxref("Blob")}} aufgelöst wird.

+ +

Syntax

+ +
response.blob().then(function(myBlob) {
+  // mach etwas mit myBlob
+});
+ +

Parameter

+ +

Keine.

+ +
Hinweis: Wenn die {{domxref("Response")}} vom {{domxref("Response.type")}} her "opaque" ist, hat der resultierende {{domxref("Blob")}} eine {{domxref("Blob.size")}} von 0 und einen {{domxref("Blob.type")}} eines leeren Strings "", wodurch er für Methoden wie {{domxref("URL.createObjectURL")}} unbrauchbar wird.
+ +

Rückgabewert

+ +

Ein Promise, welches in einen {{domxref("Blob")}} aufgelöst wird.

+ +

Beispiel

+ +

In unserem Beispiel für eine Fetch Anfrage (live ausführen) erstellen wir eine neue Anfrage mit dem {{domxref("Request.Request")}} Konstruktor und rufen dann ein JPG ab. Wenn der Abruf erfolgreich ist, lesen wir mit blob() einen {{domxref("Blob")}} aus der Antwort, fügen ihn mit {{domxref("URL.createObjectURL")}} in eine Objekt-URL ein und legen diese URL als Quelle für das {{htmlelement("img")}} Element zum Anzeigen des Bildes fest.

+ +
var myImage = document.querySelector('img');
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest)
+.then(function(response) {
+  return response.blob();
+})
+.then(function(myBlob) {
+  var objectURL = URL.createObjectURL(myBlob);
+  myImage.src = objectURL;
+});
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-blob','blob()')}}{{Spec2('Fetch')}} 
+ +

Browserkompatibilität

+ + + +

{{Compat("api.Body.blob")}}

+ +

Siehe auch

+ + diff --git a/files/de/orphaned/web/api/body/body/index.html b/files/de/orphaned/web/api/body/body/index.html new file mode 100644 index 0000000000..efbc980692 --- /dev/null +++ b/files/de/orphaned/web/api/body/body/index.html @@ -0,0 +1,87 @@ +--- +title: Body.body +slug: orphaned/Web/API/Body/body +translation_of: Web/API/Body/body +original_slug: Web/API/Body/body +--- +
{{APIRef("Fetch")}}{{seecompattable}}
+ +

Die schreibgeschützte body Eigenschaft des {{domxref("Body")}} Mixin ist ein einfacher Getter, der dazu benutzt wird den Inhalt des Body als {{domxref("ReadableStream")}} bereitzustellen.

+ +

Syntax

+ +
var stream = responseInstance.body;
+ +

Wert

+ +

Ein {{domxref("ReadableStream")}}.

+ +

Beispiel

+ +

In unserem einfachen Stream-Pump-Beispiel rufen wir ein Bild ab, machen den Antwort-Stream mit response.body sichtbar, erstellen einen Reader mit {{domxref("ReadableStream.getReader()")}} und reihen die Teile des Streams in einen zweiten, benutzerdefinierten, lesbaren Stream — wodurch wie eine exakte Kopie des Bilds erhalten.

+ +
const image = document.getElementById('target');
+
+// Bild holen
+fetch('./tortoise.png')
+// Body als ReadableStream abrufen
+.then(response => response.body)
+.then(body => {
+  const reader = body.getReader();
+
+  return new ReadableStream({
+    start(controller) {
+      return pump();
+
+      function pump() {
+        return reader.read().then(({ done, value }) => {
+          // Stream schließen, wenn keine weiteren Daten verarbeitet werden müssen
+          if (done) {
+            controller.close();
+            return;
+          }
+
+          // Das nächste Datenstück in unseren Ziel-Stream einreihen
+          controller.enqueue(value);
+          return pump();
+        });
+      }
+    }
+  })
+})
+.then(stream => new Response(stream))
+.then(response => response.blob())
+.then(blob => URL.createObjectURL(blob))
+.then(url => console.log(image.src = url))
+.catch(err => console.error(err));
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-body','body')}}{{Spec2('Fetch')}} 
+ +

Browserkompatibilität

+ + + +

{{Compat("api.Body.body")}}

+ +

Siehe auch

+ + diff --git a/files/de/orphaned/web/api/body/bodyused/index.html b/files/de/orphaned/web/api/body/bodyused/index.html new file mode 100644 index 0000000000..7f79171ea5 --- /dev/null +++ b/files/de/orphaned/web/api/body/bodyused/index.html @@ -0,0 +1,74 @@ +--- +title: Body.bodyUsed +slug: orphaned/Web/API/Body/bodyUsed +translation_of: Web/API/Body/bodyUsed +original_slug: Web/API/Body/bodyUsed +--- +
{{APIRef("Fetch")}}
+ +

Die schreibgeschützte bodyUsed Eigenschaft des {{domxref("Body")}} Mixin enthält einen {{domxref("Boolean")}} der angibt, ob der Body schon eingelesen wurde.

+ +

Syntax

+ +
var myBodyUsed = response.bodyUsed;
+ +

Wert

+ +

Ein {{domxref("Boolean")}}.

+ +

Beispiel

+ +

In unserem Beispiel für eine Fetch Anfrage (live ausführen) erstellen wir eine neue Anforderung mit dem {{domxref("Request.Request")}} Konstruktor und rufen dann ein JPG ab. Wenn der Abruf erfolgreich ist, lesen wir mit blob() einen {{domxref("Blob")}} aus der Antwort, fügen ihn mit {{domxref("URL.createObjectURL")}} in eine Objekt-URL ein und legen diese URL als Quelle für das {{htmlelement("img")}} Element zum Anzeigen des Bildes fest.

+ +

Beachten Sie, dass wir response.bodyUsed vor dem Aufruf von response.blob () und einmal danach in der Konsole protokollieren. Dies gibt vorher false zurück und anschließend true, da der Body ab diesem Punkt gelesen wurde.

+ +

HTML Inhalt

+ +
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
+
+ +

JavaScript Inhalt

+ +
var myImage = document.querySelector('.my-image');
+fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg').then(function(response) {
+    console.log(response.bodyUsed);
+    var res = response.blob();
+    console.log(response.bodyUsed);
+    return res;
+}).then(function(response) {
+    var objectURL = URL.createObjectURL(response);
+    myImage.src = objectURL;
+});
+ +

{{ EmbedLiveSample('Example', '100%', '250px') }}

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-bodyused','bodyUsed')}}{{Spec2('Fetch')}} 
+ +

Browserkompatibilität

+ + + +

{{Compat("api.Body.bodyUsed")}}

+ +

Siehe auch

+ + diff --git a/files/de/orphaned/web/api/body/formdata/index.html b/files/de/orphaned/web/api/body/formdata/index.html new file mode 100644 index 0000000000..f2539ff41a --- /dev/null +++ b/files/de/orphaned/web/api/body/formdata/index.html @@ -0,0 +1,63 @@ +--- +title: Body.formData() +slug: orphaned/Web/API/Body/formData +translation_of: Web/API/Body/formData +original_slug: Web/API/Body/formData +--- +
{{APIRef("Fetch")}}
+ +

Die Methode formData() des {{domxref("Body")}} Mixin nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Sie gibt ein Promise zurück, welches in ein {{domxref("FormData")}} Objekt aufgelöst wird.

+ +
+

Hinweis: Dies ist hauptsächlich für Service Worker relevant. Wenn ein Benutzer ein Formular absendet und ein Service Worker die Anfrage abfängt, könnten Sie bspw. formData() aufrufen, um eine Key-Value-Abbildung zu erhalten, einige Felder zu modifizieren und das Formular dann an den Server weiterzuschicken (oder lokal zu benutzen).

+
+ +

Syntax

+ +
response.formData()
+.then(function(formdata) {
+  // machen Sie etwas mit Ihren Formulardaten
+});
+ +

Parameter

+ +

Keine.

+ +

Rückgabewert

+ +

Ein Promise, welches in ein {{domxref("FormData")}} Objekt aufgelöst wird.

+ +

Beispiel

+ +

Wird nachgereicht.

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-formdata','formData()')}}{{Spec2('Fetch')}} 
+ +

Browserkompatibilität

+ + + +

{{Compat("api.Body.formData")}}

+ +

Siehe auch

+ + diff --git a/files/de/orphaned/web/api/body/index.html b/files/de/orphaned/web/api/body/index.html new file mode 100644 index 0000000000..346e7b2286 --- /dev/null +++ b/files/de/orphaned/web/api/body/index.html @@ -0,0 +1,100 @@ +--- +title: Body +slug: orphaned/Web/API/Body +tags: + - API + - BODY + - Experimental + - Fetch + - Fetch API + - Interface + - NeedsTranslation + - Reference + - TopicStub + - request +translation_of: Web/API/Body +original_slug: Web/API/Body +--- +
{{ APIRef("Fetch") }}
+ +

The Body {{glossary("mixin")}} of the Fetch API represents the body of the response/request, allowing you to declare what its content type is and how it should be handled.

+ +

Body is implemented by both {{domxref("Request")}} and {{domxref("Response")}}. This provides these objects with an associated body (a stream), a used flag (initially unset), and a MIME type (initially the empty byte sequence).

+ +

Properties

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
A simple getter used to expose a {{domxref("ReadableStream")}} of the body contents.
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
A {{domxref("Boolean")}} that indicates whether the body has been read.
+
+ +

Methods

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{domxref("ArrayBuffer")}}.
+
{{domxref("Body.blob()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("Blob")}}.
+
{{domxref("Body.formData()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("FormData")}} object.
+
{{domxref("Body.json()")}}
+
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")}}.
+
{{domxref("Body.text()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("USVString")}} (text). The response is always decoded using UTF-8.
+
+ +

Examples

+ +

The example below uses a simple fetch call to grab an image and display it in an {{htmlelement("img")}} tag. You'll notice that since we are requesting an image, we need to run {{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} implements body) to give the response its correct MIME type.

+ +

HTML Content

+ +
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
+
+ +

JS Content

+ +
const myImage = document.querySelector('.my-image');
+fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
+	.then(res => res.blob())
+	.then(res => {
+		const objectURL = URL.createObjectURL(res);
+		myImage.src = objectURL;
+});
+ +

{{ EmbedLiveSample('Examples', '100%', '250px') }}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.Body")}}

+ +

See also

+ + + +

 

diff --git a/files/de/orphaned/web/api/body/json/index.html b/files/de/orphaned/web/api/body/json/index.html new file mode 100644 index 0000000000..78d75327d9 --- /dev/null +++ b/files/de/orphaned/web/api/body/json/index.html @@ -0,0 +1,74 @@ +--- +title: Body.json() +slug: orphaned/Web/API/Body/json +translation_of: Web/API/Body/json +original_slug: Web/API/Body/json +--- +
{{APIRef("Fetch")}}
+ +

Die Methode json() des {{domxref("Body")}} Mixin nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Sie gibt ein Promise zurück, welches den Inhalt des Body als {{jsxref("JSON")}} einliest.

+ +

Syntax

+ +
response.json().then(function(data) {
+  // mach etwas mit data
+});
+ +

Parameter

+ +

Keine.

+ +

Rückgabewert

+ +

Ein Promise, welches den Inhalt des Body als {{jsxref("JSON")}} einliest. Dies kann alles sein, was als JSON abgebildet werden kann — ein Objekt, ein Array, ein String, eine Zahl...

+ +

Beispiel

+ +

In unserem Beispiel für den Abruf eines json (live ausführen) erstellen wir eine neue Anfrage mit dem {{domxref("Request.Request")}} Konstruktor und rufen dann eine .json Datei ab. Wenn der Abruf erfolgreich ist lesen wir die Daten ein und parsen sie mit json(), lesen die Werte erwartungsgemäß aus und fügen sie in eine Liste ein um unsere Produktdaten anzuzeigen.

+ +
var myList = document.querySelector('ul');
+
+var myRequest = new Request('products.json');
+
+fetch(myRequest)
+  .then(function(response) { return response.json(); })
+  .then(function(data) {
+    for (var i = 0; i < data.products.length; i++) {
+      var listItem = document.createElement('li');
+      listItem.innerHTML = '<strong>' + data.products[i].Name + '</strong> befindet sich in ' +
+                           data.products[i].Location +
+                           '. Preis: <strong>' + data.products[i].Price + '€</strong>';
+      myList.appendChild(listItem);
+    }
+  });
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-json','json()')}}{{Spec2('Fetch')}} 
+ +

Browserkompatibilität

+ + + +

{{Compat("api.Body.json")}}

+ +

Siehe auch

+ + diff --git a/files/de/orphaned/web/api/body/text/index.html b/files/de/orphaned/web/api/body/text/index.html new file mode 100644 index 0000000000..43c6dc54a2 --- /dev/null +++ b/files/de/orphaned/web/api/body/text/index.html @@ -0,0 +1,81 @@ +--- +title: Body.text() +slug: orphaned/Web/API/Body/text +translation_of: Web/API/Body/text +original_slug: Web/API/Body/text +--- +
{{APIRef("Fetch")}}
+ +

Die Methode text() des {{domxref("Body")}} Mixin nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Sie gibt ein Promise zurück, welches in ein {{domxref("USVString")}} Objekt (Text) aufgelöst wird. Die Antwort wird immer mit UTF-8 dekodiert.

+ +

Syntax

+ +
response.text().then(function (text) {
+  // do something with the text response
+});
+ +

Parameter

+ +

Keine.

+ +

Rückgabewert

+ +

Ein Promise, welches in einen {{domxref("USVString")}} aufgelöst wird.

+ +

Beispiel

+ +

In unserem Beispiel für den Abruf von Text (live ausführen) haben wir ein {{htmlelement("article")}} Element und drei Links (im Array myLinks gespeichert). Zuerst durchlaufen wir all diese, damit alle einen onclick Event Handler bekommen, der die Funktion getData() ausführt — der Bezeichner data-page des Links wird dabei als Argument übergeben — wenn einer der Links geklickt wird.

+ +

Wenn getData() ausgeführt wird erstellen wie eine Anfrage mit dem {{domxref("Request.Request")}} Konstruktor und rufen dann eine .txt Datei ab. Wenn der Abruf erfolgreich ist lesen wir das {{jsxref("USVString")}} (Text) Objekt aus der Antwort mit text() und setzen dann {{domxref("Element.innerHTML","innerHTML")}} des {{htmlelement("article")}} Elements auf den Wert des Text-Objekts.

+ +
var myArticle = document.querySelector('article');
+var myLinks = document.querySelectorAll('ul a');
+
+for(i = 0; i <= myLinks.length-1; i++) {
+  myLinks[i].onclick = function(e) {
+    e.preventDefault();
+    var linkData = e.target.getAttribute('data-page');
+    getData(linkData);
+  }
+};
+
+function getData(pageId) {
+  console.log(pageId);
+  var myRequest = new Request(pageId + '.txt');
+  fetch(myRequest).then(function(response) {
+    return response.text().then(function(text) {
+      myArticle.innerHTML = text;
+    });
+  });
+}
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-text','text()')}}{{Spec2('Fetch')}} 
+ +

Browserkompatibilität

+ + + +

{{Compat("api.Body.text")}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/body/arraybuffer/index.html b/files/de/web/api/body/arraybuffer/index.html deleted file mode 100644 index 7550dfadc8..0000000000 --- a/files/de/web/api/body/arraybuffer/index.html +++ /dev/null @@ -1,87 +0,0 @@ ---- -title: Body.arrayBuffer() -slug: Web/API/Body/arrayBuffer -translation_of: Web/API/Body/arrayBuffer ---- -
{{APIRef("Fetch")}}
- -

Die Methode arrayBuffer() des {{domxref("Body")}} Mixin nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Sie gibt ein Promise zurück, welches in einen {{domxref("ArrayBuffer")}} aufgelöst wird.

- -

Syntax

- -
response.arrayBuffer().then(function(buffer) {
-  // mach etwas mit dem Buffer
-});
- -

Parameter

- -

Keine.

- -

Rückgabewert

- -

Ein Promise, welches in einen {{domxref("ArrayBuffer")}} aufgelöst wird.

- -

Beispiel

- -

In unserem Live-Beispiel zum Abruf eines Array Buffers haben wir einen Wiedergabe-Knopf. Bei einem Klick darauf wird die Funktion getData() ausgeführt. Beachten Sie, dass vor der Wiedergabe die ganze Audio-Datei heruntergeladen wird. Benötigen Sie eine Wiedergabe noch während des Downloads (Streaming) ziehen Sie {{domxref("HTMLAudioElement")}} in Betracht:

- -
new Audio(music.ogg).play()
-
- -

In getData() erstellen wir eine neue Anfrage mit dem {{domxref("Request.Request")}} Konstruktor, um dann einen OGG Musik-Track abzurufen. Wir benutzen ebenfalls {{domxref("AudioContext.createBufferSource")}} um eine Audio-Puffer-Quelle zu erstellen. Ist der Abruf erfolgreich, lesen wir mit arrayBuffer() einen {{domxref("ArrayBuffer")}} aus der Antwort, dekodieren die Audiodaten mit {{domxref("AudioContext.decodeAudioData")}}, setzen die dekodierten Daten als Quelle für den Audio-Puffer fest und verbinden die Quelle mit {{domxref("AudioContext.destination")}}.

- -

Wenn getData() durchgelaufen ist, starten wir die Wiedergabe mit start(0) und deaktivieren den Wiedergabe-Knopf, damit er nicht erneut geklickt werden kann, während die Wiedergabe läuft (was zu einem Fehler führen würde).

- -
function getData() {
-  source = audioCtx.createBufferSource();
-
-  var myRequest = new Request('viper.ogg');
-
-  fetch(myRequest).then(function(response) {
-    return response.arrayBuffer();
-  }).then(function(buffer) {
-    audioCtx.decodeAudioData(buffer, function(decodedData) {
-      source.buffer = decodedData;
-      source.connect(audioCtx.destination);
-    });
-  });
-};
-
-// Knöpfe zum Abspielen und Anhalten verknüpfen
-
-play.onclick = function() {
-  getData();
-  source.start(0);
-  play.setAttribute('disabled', 'disabled');
-}
- -

Spezifikationen

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-arraybuffer','arrayBuffer()')}}{{Spec2('Fetch')}} 
- -

Browserkompatibilität

- - - -

{{Compat("api.Body.arrayBuffer")}}

- -

Siehe auch

- - diff --git a/files/de/web/api/body/blob/index.html b/files/de/web/api/body/blob/index.html deleted file mode 100644 index 53595fdbda..0000000000 --- a/files/de/web/api/body/blob/index.html +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Body.blob() -slug: Web/API/Body/blob -translation_of: Web/API/Body/blob ---- -
{{APIRef("Fetch")}}
- -

Die Methode blob() des {{domxref("Body")}} Mixin nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Sie gibt ein Promise zurück, welches in einen {{domxref("Blob")}} aufgelöst wird.

- -

Syntax

- -
response.blob().then(function(myBlob) {
-  // mach etwas mit myBlob
-});
- -

Parameter

- -

Keine.

- -
Hinweis: Wenn die {{domxref("Response")}} vom {{domxref("Response.type")}} her "opaque" ist, hat der resultierende {{domxref("Blob")}} eine {{domxref("Blob.size")}} von 0 und einen {{domxref("Blob.type")}} eines leeren Strings "", wodurch er für Methoden wie {{domxref("URL.createObjectURL")}} unbrauchbar wird.
- -

Rückgabewert

- -

Ein Promise, welches in einen {{domxref("Blob")}} aufgelöst wird.

- -

Beispiel

- -

In unserem Beispiel für eine Fetch Anfrage (live ausführen) erstellen wir eine neue Anfrage mit dem {{domxref("Request.Request")}} Konstruktor und rufen dann ein JPG ab. Wenn der Abruf erfolgreich ist, lesen wir mit blob() einen {{domxref("Blob")}} aus der Antwort, fügen ihn mit {{domxref("URL.createObjectURL")}} in eine Objekt-URL ein und legen diese URL als Quelle für das {{htmlelement("img")}} Element zum Anzeigen des Bildes fest.

- -
var myImage = document.querySelector('img');
-
-var myRequest = new Request('flowers.jpg');
-
-fetch(myRequest)
-.then(function(response) {
-  return response.blob();
-})
-.then(function(myBlob) {
-  var objectURL = URL.createObjectURL(myBlob);
-  myImage.src = objectURL;
-});
-
- -

Spezifikationen

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-blob','blob()')}}{{Spec2('Fetch')}} 
- -

Browserkompatibilität

- - - -

{{Compat("api.Body.blob")}}

- -

Siehe auch

- - diff --git a/files/de/web/api/body/body/index.html b/files/de/web/api/body/body/index.html deleted file mode 100644 index cbe7484d91..0000000000 --- a/files/de/web/api/body/body/index.html +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: Body.body -slug: Web/API/Body/body -translation_of: Web/API/Body/body ---- -
{{APIRef("Fetch")}}{{seecompattable}}
- -

Die schreibgeschützte body Eigenschaft des {{domxref("Body")}} Mixin ist ein einfacher Getter, der dazu benutzt wird den Inhalt des Body als {{domxref("ReadableStream")}} bereitzustellen.

- -

Syntax

- -
var stream = responseInstance.body;
- -

Wert

- -

Ein {{domxref("ReadableStream")}}.

- -

Beispiel

- -

In unserem einfachen Stream-Pump-Beispiel rufen wir ein Bild ab, machen den Antwort-Stream mit response.body sichtbar, erstellen einen Reader mit {{domxref("ReadableStream.getReader()")}} und reihen die Teile des Streams in einen zweiten, benutzerdefinierten, lesbaren Stream — wodurch wie eine exakte Kopie des Bilds erhalten.

- -
const image = document.getElementById('target');
-
-// Bild holen
-fetch('./tortoise.png')
-// Body als ReadableStream abrufen
-.then(response => response.body)
-.then(body => {
-  const reader = body.getReader();
-
-  return new ReadableStream({
-    start(controller) {
-      return pump();
-
-      function pump() {
-        return reader.read().then(({ done, value }) => {
-          // Stream schließen, wenn keine weiteren Daten verarbeitet werden müssen
-          if (done) {
-            controller.close();
-            return;
-          }
-
-          // Das nächste Datenstück in unseren Ziel-Stream einreihen
-          controller.enqueue(value);
-          return pump();
-        });
-      }
-    }
-  })
-})
-.then(stream => new Response(stream))
-.then(response => response.blob())
-.then(blob => URL.createObjectURL(blob))
-.then(url => console.log(image.src = url))
-.catch(err => console.error(err));
- -

Spezifikationen

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-body','body')}}{{Spec2('Fetch')}} 
- -

Browserkompatibilität

- - - -

{{Compat("api.Body.body")}}

- -

Siehe auch

- - diff --git a/files/de/web/api/body/bodyused/index.html b/files/de/web/api/body/bodyused/index.html deleted file mode 100644 index 052e8fcc7c..0000000000 --- a/files/de/web/api/body/bodyused/index.html +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Body.bodyUsed -slug: Web/API/Body/bodyUsed -translation_of: Web/API/Body/bodyUsed ---- -
{{APIRef("Fetch")}}
- -

Die schreibgeschützte bodyUsed Eigenschaft des {{domxref("Body")}} Mixin enthält einen {{domxref("Boolean")}} der angibt, ob der Body schon eingelesen wurde.

- -

Syntax

- -
var myBodyUsed = response.bodyUsed;
- -

Wert

- -

Ein {{domxref("Boolean")}}.

- -

Beispiel

- -

In unserem Beispiel für eine Fetch Anfrage (live ausführen) erstellen wir eine neue Anforderung mit dem {{domxref("Request.Request")}} Konstruktor und rufen dann ein JPG ab. Wenn der Abruf erfolgreich ist, lesen wir mit blob() einen {{domxref("Blob")}} aus der Antwort, fügen ihn mit {{domxref("URL.createObjectURL")}} in eine Objekt-URL ein und legen diese URL als Quelle für das {{htmlelement("img")}} Element zum Anzeigen des Bildes fest.

- -

Beachten Sie, dass wir response.bodyUsed vor dem Aufruf von response.blob () und einmal danach in der Konsole protokollieren. Dies gibt vorher false zurück und anschließend true, da der Body ab diesem Punkt gelesen wurde.

- -

HTML Inhalt

- -
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
-
- -

JavaScript Inhalt

- -
var myImage = document.querySelector('.my-image');
-fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg').then(function(response) {
-    console.log(response.bodyUsed);
-    var res = response.blob();
-    console.log(response.bodyUsed);
-    return res;
-}).then(function(response) {
-    var objectURL = URL.createObjectURL(response);
-    myImage.src = objectURL;
-});
- -

{{ EmbedLiveSample('Example', '100%', '250px') }}

- -

Spezifikationen

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-bodyused','bodyUsed')}}{{Spec2('Fetch')}} 
- -

Browserkompatibilität

- - - -

{{Compat("api.Body.bodyUsed")}}

- -

Siehe auch

- - diff --git a/files/de/web/api/body/formdata/index.html b/files/de/web/api/body/formdata/index.html deleted file mode 100644 index 4ceb02aeb4..0000000000 --- a/files/de/web/api/body/formdata/index.html +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Body.formData() -slug: Web/API/Body/formData -translation_of: Web/API/Body/formData ---- -
{{APIRef("Fetch")}}
- -

Die Methode formData() des {{domxref("Body")}} Mixin nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Sie gibt ein Promise zurück, welches in ein {{domxref("FormData")}} Objekt aufgelöst wird.

- -
-

Hinweis: Dies ist hauptsächlich für Service Worker relevant. Wenn ein Benutzer ein Formular absendet und ein Service Worker die Anfrage abfängt, könnten Sie bspw. formData() aufrufen, um eine Key-Value-Abbildung zu erhalten, einige Felder zu modifizieren und das Formular dann an den Server weiterzuschicken (oder lokal zu benutzen).

-
- -

Syntax

- -
response.formData()
-.then(function(formdata) {
-  // machen Sie etwas mit Ihren Formulardaten
-});
- -

Parameter

- -

Keine.

- -

Rückgabewert

- -

Ein Promise, welches in ein {{domxref("FormData")}} Objekt aufgelöst wird.

- -

Beispiel

- -

Wird nachgereicht.

- -

Spezifikationen

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-formdata','formData()')}}{{Spec2('Fetch')}} 
- -

Browserkompatibilität

- - - -

{{Compat("api.Body.formData")}}

- -

Siehe auch

- - diff --git a/files/de/web/api/body/index.html b/files/de/web/api/body/index.html deleted file mode 100644 index 3693a73653..0000000000 --- a/files/de/web/api/body/index.html +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Body -slug: Web/API/Body -tags: - - API - - BODY - - Experimental - - Fetch - - Fetch API - - Interface - - NeedsTranslation - - Reference - - TopicStub - - request -translation_of: Web/API/Body ---- -
{{ APIRef("Fetch") }}
- -

The Body {{glossary("mixin")}} of the Fetch API represents the body of the response/request, allowing you to declare what its content type is and how it should be handled.

- -

Body is implemented by both {{domxref("Request")}} and {{domxref("Response")}}. This provides these objects with an associated body (a stream), a used flag (initially unset), and a MIME type (initially the empty byte sequence).

- -

Properties

- -
-
{{domxref("Body.body")}} {{readonlyInline}}
-
A simple getter used to expose a {{domxref("ReadableStream")}} of the body contents.
-
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
-
A {{domxref("Boolean")}} that indicates whether the body has been read.
-
- -

Methods

- -
-
{{domxref("Body.arrayBuffer()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{domxref("ArrayBuffer")}}.
-
{{domxref("Body.blob()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("Blob")}}.
-
{{domxref("Body.formData()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("FormData")}} object.
-
{{domxref("Body.json()")}}
-
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")}}.
-
{{domxref("Body.text()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("USVString")}} (text). The response is always decoded using UTF-8.
-
- -

Examples

- -

The example below uses a simple fetch call to grab an image and display it in an {{htmlelement("img")}} tag. You'll notice that since we are requesting an image, we need to run {{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} implements body) to give the response its correct MIME type.

- -

HTML Content

- -
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
-
- -

JS Content

- -
const myImage = document.querySelector('.my-image');
-fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
-	.then(res => res.blob())
-	.then(res => {
-		const objectURL = URL.createObjectURL(res);
-		myImage.src = objectURL;
-});
- -

{{ EmbedLiveSample('Examples', '100%', '250px') }}

- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}} 
- -

Browser compatibility

- - - -

{{Compat("api.Body")}}

- -

See also

- - - -

 

diff --git a/files/de/web/api/body/json/index.html b/files/de/web/api/body/json/index.html deleted file mode 100644 index 76271e680d..0000000000 --- a/files/de/web/api/body/json/index.html +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Body.json() -slug: Web/API/Body/json -translation_of: Web/API/Body/json ---- -
{{APIRef("Fetch")}}
- -

Die Methode json() des {{domxref("Body")}} Mixin nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Sie gibt ein Promise zurück, welches den Inhalt des Body als {{jsxref("JSON")}} einliest.

- -

Syntax

- -
response.json().then(function(data) {
-  // mach etwas mit data
-});
- -

Parameter

- -

Keine.

- -

Rückgabewert

- -

Ein Promise, welches den Inhalt des Body als {{jsxref("JSON")}} einliest. Dies kann alles sein, was als JSON abgebildet werden kann — ein Objekt, ein Array, ein String, eine Zahl...

- -

Beispiel

- -

In unserem Beispiel für den Abruf eines json (live ausführen) erstellen wir eine neue Anfrage mit dem {{domxref("Request.Request")}} Konstruktor und rufen dann eine .json Datei ab. Wenn der Abruf erfolgreich ist lesen wir die Daten ein und parsen sie mit json(), lesen die Werte erwartungsgemäß aus und fügen sie in eine Liste ein um unsere Produktdaten anzuzeigen.

- -
var myList = document.querySelector('ul');
-
-var myRequest = new Request('products.json');
-
-fetch(myRequest)
-  .then(function(response) { return response.json(); })
-  .then(function(data) {
-    for (var i = 0; i < data.products.length; i++) {
-      var listItem = document.createElement('li');
-      listItem.innerHTML = '<strong>' + data.products[i].Name + '</strong> befindet sich in ' +
-                           data.products[i].Location +
-                           '. Preis: <strong>' + data.products[i].Price + '€</strong>';
-      myList.appendChild(listItem);
-    }
-  });
- -

Spezifikationen

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-json','json()')}}{{Spec2('Fetch')}} 
- -

Browserkompatibilität

- - - -

{{Compat("api.Body.json")}}

- -

Siehe auch

- - diff --git a/files/de/web/api/body/text/index.html b/files/de/web/api/body/text/index.html deleted file mode 100644 index 8ccc5fb358..0000000000 --- a/files/de/web/api/body/text/index.html +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Body.text() -slug: Web/API/Body/text -translation_of: Web/API/Body/text ---- -
{{APIRef("Fetch")}}
- -

Die Methode text() des {{domxref("Body")}} Mixin nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Sie gibt ein Promise zurück, welches in ein {{domxref("USVString")}} Objekt (Text) aufgelöst wird. Die Antwort wird immer mit UTF-8 dekodiert.

- -

Syntax

- -
response.text().then(function (text) {
-  // do something with the text response
-});
- -

Parameter

- -

Keine.

- -

Rückgabewert

- -

Ein Promise, welches in einen {{domxref("USVString")}} aufgelöst wird.

- -

Beispiel

- -

In unserem Beispiel für den Abruf von Text (live ausführen) haben wir ein {{htmlelement("article")}} Element und drei Links (im Array myLinks gespeichert). Zuerst durchlaufen wir all diese, damit alle einen onclick Event Handler bekommen, der die Funktion getData() ausführt — der Bezeichner data-page des Links wird dabei als Argument übergeben — wenn einer der Links geklickt wird.

- -

Wenn getData() ausgeführt wird erstellen wie eine Anfrage mit dem {{domxref("Request.Request")}} Konstruktor und rufen dann eine .txt Datei ab. Wenn der Abruf erfolgreich ist lesen wir das {{jsxref("USVString")}} (Text) Objekt aus der Antwort mit text() und setzen dann {{domxref("Element.innerHTML","innerHTML")}} des {{htmlelement("article")}} Elements auf den Wert des Text-Objekts.

- -
var myArticle = document.querySelector('article');
-var myLinks = document.querySelectorAll('ul a');
-
-for(i = 0; i <= myLinks.length-1; i++) {
-  myLinks[i].onclick = function(e) {
-    e.preventDefault();
-    var linkData = e.target.getAttribute('data-page');
-    getData(linkData);
-  }
-};
-
-function getData(pageId) {
-  console.log(pageId);
-  var myRequest = new Request(pageId + '.txt');
-  fetch(myRequest).then(function(response) {
-    return response.text().then(function(text) {
-      myArticle.innerHTML = text;
-    });
-  });
-}
- -

Spezifikationen

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-text','text()')}}{{Spec2('Fetch')}} 
- -

Browserkompatibilität

- - - -

{{Compat("api.Body.text")}}

- -

Siehe auch

- - diff --git a/files/es/_redirects.txt b/files/es/_redirects.txt index b837bed45f..21e06034fe 100644 --- a/files/es/_redirects.txt +++ b/files/es/_redirects.txt @@ -1777,6 +1777,9 @@ /es/docs/Web/API/BatteryManager.onchargingchange /es/docs/Web/API/BatteryManager/onchargingchange /es/docs/Web/API/BatteryManager.onlevelchange /es/docs/Web/API/BatteryManager/onlevelchange /es/docs/Web/API/Blob.Blob /es/docs/Web/API/Blob/Blob +/es/docs/Web/API/Body /es/docs/orphaned/Web/API/Body +/es/docs/Web/API/Body/formData /es/docs/orphaned/Web/API/Body/formData +/es/docs/Web/API/Body/json /es/docs/orphaned/Web/API/Body/json /es/docs/Web/API/CSSStyleSheet.insertRule /es/docs/Web/API/CSSStyleSheet/insertRule /es/docs/Web/API/CameraCapabilities.maxExposureCompensation /es/docs/Web/API/CameraCapabilities/maxExposureCompensation /es/docs/Web/API/CameraCapabilities.maxFocusAreas /es/docs/Web/API/CameraCapabilities/maxFocusAreas diff --git a/files/es/_wikihistory.json b/files/es/_wikihistory.json index cf75d92e56..267e001de5 100644 --- a/files/es/_wikihistory.json +++ b/files/es/_wikihistory.json @@ -5190,25 +5190,6 @@ "japho" ] }, - "Web/API/Body": { - "modified": "2020-10-15T22:17:35.545Z", - "contributors": [ - "SphinxKnight", - "bigblair81" - ] - }, - "Web/API/Body/formData": { - "modified": "2020-10-15T22:17:33.164Z", - "contributors": [ - "brauni800" - ] - }, - "Web/API/Body/json": { - "modified": "2020-10-15T22:29:20.361Z", - "contributors": [ - "camsa" - ] - }, "Web/API/CSSRule": { "modified": "2019-03-23T23:58:11.498Z", "contributors": [ @@ -23212,6 +23193,25 @@ "guiller1998" ] }, + "orphaned/Web/API/Body": { + "modified": "2020-10-15T22:17:35.545Z", + "contributors": [ + "SphinxKnight", + "bigblair81" + ] + }, + "orphaned/Web/API/Body/formData": { + "modified": "2020-10-15T22:17:33.164Z", + "contributors": [ + "brauni800" + ] + }, + "orphaned/Web/API/Body/json": { + "modified": "2020-10-15T22:29:20.361Z", + "contributors": [ + "camsa" + ] + }, "orphaned/Web/API/ChildNode": { "modified": "2019-03-29T14:12:39.589Z", "contributors": [ diff --git a/files/es/orphaned/web/api/body/formdata/index.html b/files/es/orphaned/web/api/body/formdata/index.html new file mode 100644 index 0000000000..a7cb72413c --- /dev/null +++ b/files/es/orphaned/web/api/body/formdata/index.html @@ -0,0 +1,73 @@ +--- +title: Body.formData() +slug: orphaned/Web/API/Body/formData +tags: + - API + - BODY + - Experimental + - Fetch + - Fetch API + - FormData + - Method + - NeedsExample + - Reference +translation_of: Web/API/Body/formData +original_slug: Web/API/Body/formData +--- +
{{APIRef("Fetch")}}
+ +

El método formData() de {{domxref("Body")}} mixin toma una cadena {{domxref("Response")}} y la lee completamente. Esto devuelve una promesa que resuelve con un objeto {{domxref("FormData")}}.

+ +
+

Nota: Esto es principalmente relevante en service workers. Si un usuario envia un formulario y un service worker intercepta el request, tu por ejemplo podrás llamar a formData() para obtener un mapeo del tipo llave-valor, modificar algunos campos, luego enviar el formulario al servidor (o utilizarlo localmente).

+
+ +

Sintaxis

+ +
response.formData()
+.then(function(formdata) {
+  // hacer algo con tu formdata
+});
+ +

Parámetros

+ +

Ninguno.

+ +

Valor de retorno

+ +

Una {{domxref("Promise")}} que resuelve con un objeto {{domxref("FormData")}}.

+ +

Ejemplo

+ +

TBD.

+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('Fetch','#dom-body-formdata','formData()')}}{{Spec2('Fetch')}} 
+ +

Compatibilidad en navegadores

+ + + +

{{Compat("api.Body.formData")}}

+ +

Ver también

+ + diff --git a/files/es/orphaned/web/api/body/index.html b/files/es/orphaned/web/api/body/index.html new file mode 100644 index 0000000000..346e7b2286 --- /dev/null +++ b/files/es/orphaned/web/api/body/index.html @@ -0,0 +1,100 @@ +--- +title: Body +slug: orphaned/Web/API/Body +tags: + - API + - BODY + - Experimental + - Fetch + - Fetch API + - Interface + - NeedsTranslation + - Reference + - TopicStub + - request +translation_of: Web/API/Body +original_slug: Web/API/Body +--- +
{{ APIRef("Fetch") }}
+ +

The Body {{glossary("mixin")}} of the Fetch API represents the body of the response/request, allowing you to declare what its content type is and how it should be handled.

+ +

Body is implemented by both {{domxref("Request")}} and {{domxref("Response")}}. This provides these objects with an associated body (a stream), a used flag (initially unset), and a MIME type (initially the empty byte sequence).

+ +

Properties

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
A simple getter used to expose a {{domxref("ReadableStream")}} of the body contents.
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
A {{domxref("Boolean")}} that indicates whether the body has been read.
+
+ +

Methods

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{domxref("ArrayBuffer")}}.
+
{{domxref("Body.blob()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("Blob")}}.
+
{{domxref("Body.formData()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("FormData")}} object.
+
{{domxref("Body.json()")}}
+
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")}}.
+
{{domxref("Body.text()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("USVString")}} (text). The response is always decoded using UTF-8.
+
+ +

Examples

+ +

The example below uses a simple fetch call to grab an image and display it in an {{htmlelement("img")}} tag. You'll notice that since we are requesting an image, we need to run {{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} implements body) to give the response its correct MIME type.

+ +

HTML Content

+ +
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
+
+ +

JS Content

+ +
const myImage = document.querySelector('.my-image');
+fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
+	.then(res => res.blob())
+	.then(res => {
+		const objectURL = URL.createObjectURL(res);
+		myImage.src = objectURL;
+});
+ +

{{ EmbedLiveSample('Examples', '100%', '250px') }}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.Body")}}

+ +

See also

+ + + +

 

diff --git a/files/es/orphaned/web/api/body/json/index.html b/files/es/orphaned/web/api/body/json/index.html new file mode 100644 index 0000000000..35f7811df3 --- /dev/null +++ b/files/es/orphaned/web/api/body/json/index.html @@ -0,0 +1,83 @@ +--- +title: Body.json() +slug: orphaned/Web/API/Body/json +translation_of: Web/API/Body/json +original_slug: Web/API/Body/json +--- +
{{APIRef("Fetch API")}}
+ +

El método json() de {{DOMxRef("Body")}} recibe un flujo de datos {{DOMxRef("Response")}} y lo lee a término. Devuelve una promesa con el cuerpo del texto transformado a {{JSxRef("JSON")}}.

+ +

Sintáxis

+ +
response.json().then(data => {
+  // do something with your data
+});
+ +

Parámetros

+ +

No.

+ +

Valor devuelto

+ +

Una {{jsxref("Promise")}} que se resuelve a un objeto JavaScript. Este objeto puede ser cualquier cosa que pueda ser representada por JSON (un objeto, un array, una cadena de caracteres, un número...).

+ +

Example

+ +

In our fetch json example (run fetch json live), we create a new request using the {{DOMxRef("Request.Request", "Request()")}} constructor, then use it to fetch a .json file. When the fetch is successful, we read and parse the data using json(), then read values out of the resulting objects as you'd expect and insert them into list items to display our product data.

+ +
const myList = document.querySelector('ul');
+const myRequest = new Request('products.json');
+
+fetch(myRequest)
+  .then(response => response.json())
+  .then(data => {
+    for (const product of data.products) {
+      let listItem = document.createElement('li');
+      listItem.appendChild(
+        document.createElement('strong')
+      ).textContent = product.Name;
+      listItem.append(
+        ` can be found in ${
+          product.Location
+        }. Cost: `
+      );
+      listItem.appendChild(
+        document.createElement('strong')
+      ).textContent = `£${product.Price}`;
+      myList.appendChild(listItem);
+    }
+  });
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Fetch", "#dom-body-json", "Body.json()")}}{{Spec2("Fetch")}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.Body.json")}}

+ +

See also

+ + diff --git a/files/es/web/api/body/formdata/index.html b/files/es/web/api/body/formdata/index.html deleted file mode 100644 index b095fba9b3..0000000000 --- a/files/es/web/api/body/formdata/index.html +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Body.formData() -slug: Web/API/Body/formData -tags: - - API - - BODY - - Experimental - - Fetch - - Fetch API - - FormData - - Method - - NeedsExample - - Reference -translation_of: Web/API/Body/formData ---- -
{{APIRef("Fetch")}}
- -

El método formData() de {{domxref("Body")}} mixin toma una cadena {{domxref("Response")}} y la lee completamente. Esto devuelve una promesa que resuelve con un objeto {{domxref("FormData")}}.

- -
-

Nota: Esto es principalmente relevante en service workers. Si un usuario envia un formulario y un service worker intercepta el request, tu por ejemplo podrás llamar a formData() para obtener un mapeo del tipo llave-valor, modificar algunos campos, luego enviar el formulario al servidor (o utilizarlo localmente).

-
- -

Sintaxis

- -
response.formData()
-.then(function(formdata) {
-  // hacer algo con tu formdata
-});
- -

Parámetros

- -

Ninguno.

- -

Valor de retorno

- -

Una {{domxref("Promise")}} que resuelve con un objeto {{domxref("FormData")}}.

- -

Ejemplo

- -

TBD.

- -

Especificaciones

- - - - - - - - - - - - - - -
EspecificaciónEstadoComentario
{{SpecName('Fetch','#dom-body-formdata','formData()')}}{{Spec2('Fetch')}} 
- -

Compatibilidad en navegadores

- - - -

{{Compat("api.Body.formData")}}

- -

Ver también

- - diff --git a/files/es/web/api/body/index.html b/files/es/web/api/body/index.html deleted file mode 100644 index 3693a73653..0000000000 --- a/files/es/web/api/body/index.html +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Body -slug: Web/API/Body -tags: - - API - - BODY - - Experimental - - Fetch - - Fetch API - - Interface - - NeedsTranslation - - Reference - - TopicStub - - request -translation_of: Web/API/Body ---- -
{{ APIRef("Fetch") }}
- -

The Body {{glossary("mixin")}} of the Fetch API represents the body of the response/request, allowing you to declare what its content type is and how it should be handled.

- -

Body is implemented by both {{domxref("Request")}} and {{domxref("Response")}}. This provides these objects with an associated body (a stream), a used flag (initially unset), and a MIME type (initially the empty byte sequence).

- -

Properties

- -
-
{{domxref("Body.body")}} {{readonlyInline}}
-
A simple getter used to expose a {{domxref("ReadableStream")}} of the body contents.
-
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
-
A {{domxref("Boolean")}} that indicates whether the body has been read.
-
- -

Methods

- -
-
{{domxref("Body.arrayBuffer()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{domxref("ArrayBuffer")}}.
-
{{domxref("Body.blob()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("Blob")}}.
-
{{domxref("Body.formData()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("FormData")}} object.
-
{{domxref("Body.json()")}}
-
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")}}.
-
{{domxref("Body.text()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("USVString")}} (text). The response is always decoded using UTF-8.
-
- -

Examples

- -

The example below uses a simple fetch call to grab an image and display it in an {{htmlelement("img")}} tag. You'll notice that since we are requesting an image, we need to run {{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} implements body) to give the response its correct MIME type.

- -

HTML Content

- -
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
-
- -

JS Content

- -
const myImage = document.querySelector('.my-image');
-fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
-	.then(res => res.blob())
-	.then(res => {
-		const objectURL = URL.createObjectURL(res);
-		myImage.src = objectURL;
-});
- -

{{ EmbedLiveSample('Examples', '100%', '250px') }}

- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}} 
- -

Browser compatibility

- - - -

{{Compat("api.Body")}}

- -

See also

- - - -

 

diff --git a/files/es/web/api/body/json/index.html b/files/es/web/api/body/json/index.html deleted file mode 100644 index 54c8d75d12..0000000000 --- a/files/es/web/api/body/json/index.html +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: Body.json() -slug: Web/API/Body/json -translation_of: Web/API/Body/json ---- -
{{APIRef("Fetch API")}}
- -

El método json() de {{DOMxRef("Body")}} recibe un flujo de datos {{DOMxRef("Response")}} y lo lee a término. Devuelve una promesa con el cuerpo del texto transformado a {{JSxRef("JSON")}}.

- -

Sintáxis

- -
response.json().then(data => {
-  // do something with your data
-});
- -

Parámetros

- -

No.

- -

Valor devuelto

- -

Una {{jsxref("Promise")}} que se resuelve a un objeto JavaScript. Este objeto puede ser cualquier cosa que pueda ser representada por JSON (un objeto, un array, una cadena de caracteres, un número...).

- -

Example

- -

In our fetch json example (run fetch json live), we create a new request using the {{DOMxRef("Request.Request", "Request()")}} constructor, then use it to fetch a .json file. When the fetch is successful, we read and parse the data using json(), then read values out of the resulting objects as you'd expect and insert them into list items to display our product data.

- -
const myList = document.querySelector('ul');
-const myRequest = new Request('products.json');
-
-fetch(myRequest)
-  .then(response => response.json())
-  .then(data => {
-    for (const product of data.products) {
-      let listItem = document.createElement('li');
-      listItem.appendChild(
-        document.createElement('strong')
-      ).textContent = product.Name;
-      listItem.append(
-        ` can be found in ${
-          product.Location
-        }. Cost: `
-      );
-      listItem.appendChild(
-        document.createElement('strong')
-      ).textContent = `£${product.Price}`;
-      myList.appendChild(listItem);
-    }
-  });
- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("Fetch", "#dom-body-json", "Body.json()")}}{{Spec2("Fetch")}}Initial definition
- -

Browser compatibility

- - - -

{{Compat("api.Body.json")}}

- -

See also

- - diff --git a/files/fr/_redirects.txt b/files/fr/_redirects.txt index 02bf9e3a43..1326e07509 100644 --- a/files/fr/_redirects.txt +++ b/files/fr/_redirects.txt @@ -3601,6 +3601,8 @@ /fr/docs/Web/API/AnimationEvent.pseudoElement /fr/docs/Web/API/AnimationEvent/pseudoElement /fr/docs/Web/API/Apps.mgmt.getAll /fr/docs/Web/API/DomApplicationsManager/getAll /fr/docs/Web/API/AudioContext/createGain /fr/docs/Web/API/BaseAudioContext/createGain +/fr/docs/Web/API/Body /fr/docs/orphaned/Web/API/Body +/fr/docs/Web/API/Body/json /fr/docs/orphaned/Web/API/Body/json /fr/docs/Web/API/CSSMatrix /fr/docs/Web/API/DOMMatrix /fr/docs/Web/API/Canvas_API/Tutoriel_canvas /fr/docs/Web/API/Canvas_API/Tutorial /fr/docs/Web/API/Canvas_API/Tutoriel_canvas/Advanced_animations /fr/docs/Web/API/Canvas_API/Tutorial/Advanced_animations diff --git a/files/fr/_wikihistory.json b/files/fr/_wikihistory.json index caad5c7e4e..d52c18c79d 100644 --- a/files/fr/_wikihistory.json +++ b/files/fr/_wikihistory.json @@ -12289,26 +12289,6 @@ "loella16" ] }, - "Web/API/Body": { - "modified": "2020-10-15T22:00:04.273Z", - "contributors": [ - "Voulto", - "Retroscilo", - "Arzak656", - "SphinxKnight", - "vqrs" - ] - }, - "Web/API/Body/json": { - "modified": "2020-10-15T22:00:00.599Z", - "contributors": [ - "SphinxKnight", - "jdvauguet", - "enkienki", - "MaximeSarrato", - "Nithramir" - ] - }, "Web/API/ByteString": { "modified": "2019-03-23T22:50:30.417Z", "contributors": [ @@ -44564,6 +44544,26 @@ "SphinxKnight" ] }, + "orphaned/Web/API/Body": { + "modified": "2020-10-15T22:00:04.273Z", + "contributors": [ + "Voulto", + "Retroscilo", + "Arzak656", + "SphinxKnight", + "vqrs" + ] + }, + "orphaned/Web/API/Body/json": { + "modified": "2020-10-15T22:00:00.599Z", + "contributors": [ + "SphinxKnight", + "jdvauguet", + "enkienki", + "MaximeSarrato", + "Nithramir" + ] + }, "orphaned/Web/API/ChildNode": { "modified": "2020-10-15T21:28:06.168Z", "contributors": [ diff --git a/files/fr/orphaned/web/api/body/index.html b/files/fr/orphaned/web/api/body/index.html new file mode 100644 index 0000000000..89c70bbba0 --- /dev/null +++ b/files/fr/orphaned/web/api/body/index.html @@ -0,0 +1,97 @@ +--- +title: Body +slug: orphaned/Web/API/Body +tags: + - API + - BODY + - Experimental + - Fetch + - Fetch API + - Interface + - Reference + - TopicStub + - request +translation_of: Web/API/Body +original_slug: Web/API/Body +--- +
{{ APIRef("Fetch") }}
+ +

Le {{glossary("mixin")}} Body de l'API Fetch représente le corps de d'une requête ou d'une réponse, vous permettant de déclarer le type de son contenu et comment le manipuler.

+ +

Body est implémenté par {{domxref("Request")}} et {{domxref("Response")}}. Ces derniers fournissent un objet avec un un corps associé (un stream), un drapeaux pour indiquer si le corps a déjà été utilisé (initialisé à faux), et un type MIME (au début, une séquence vide d'octet).

+ +

Propriétés

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
Un simple getter utilisé pour obtenir un {{domxref("ReadableStream")}} du contenu.
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
Un {{jsxref("Boolean")}} qui indique si le corps a déjà été lu.
+
+ +

Méthodes

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
Prend un flux {{domxref("Response")}}, le lit en entier, et le retourne sous forme d'un {{jsxref("ArrayBuffer")}} au travers d'une promesse.
+
{{domxref("Body.blob()")}}
+
Prends un flux {{domxref("Response")}}, le lit en entier, et le retourne dans un {{domxref("Blob")}} au travers d'une promesse.
+
{{domxref("Body.formData()")}}
+
Prends un flux {{domxref("Response")}}, le lit en entier, et le retourne dans un objet {{domxref("FormData")}} au travers d'une promesse.
+
{{domxref("Body.json()")}}
+
Prends un flux {{domxref("Response")}}, le lit en entier et retourne une promesse résolue avec le résultat textuel interprété comme du {{jsxref("JSON")}}.
+
{{domxref("Body.text()")}}
+
Prend un flux {{domxref("Response")}}, le lit en entier, et le retourne dans une {{domxref("USVString")}} (texte) au travers d'une promesse. La réponse est toujours décodée en utilisant l'UTF-8.
+
+ +

Exemples

+ +

L'exemple suivant utilise un simple appel fetch pour récupérer une image et l'afficher dans un élément {{htmlelement("img")}}. Notez qu'une fois l'image téléchargée, nous devons appeler {{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} implémente body) pour connaître le MIME type correcte.

+ +

Code HTML

+ +
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
+
+ +

Code JavaScript

+ +
const myImage = document.querySelector('.my-image');
+fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
+	.then(res => res.blob())
+	.then(res => {
+		const objectURL = URL.createObjectURL(res);
+		myImage.src = objectURL;
+});
+ +

{{ EmbedLiveSample('Examples', '100%', '250px') }}

+ +

Spécifications

+ + + + + + + + + + + + + + +
SpécificationsStatusCommentaire
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}}
+ +

Compatibilité des navigateurs

+ + + +

{{Compat("api.Body")}}

+ +

Voir aussi

+ + diff --git a/files/fr/orphaned/web/api/body/json/index.html b/files/fr/orphaned/web/api/body/json/index.html new file mode 100644 index 0000000000..923ef65ebf --- /dev/null +++ b/files/fr/orphaned/web/api/body/json/index.html @@ -0,0 +1,87 @@ +--- +title: Body.json() +slug: orphaned/Web/API/Body/json +tags: + - API + - BODY + - Experimental + - Fetch + - JSON + - Méthode + - Reference +translation_of: Web/API/Body/json +original_slug: Web/API/Body/json +--- +
{{APIRef("Fetch")}}
+ +

La méthode json() de {{domxref("Body")}} lit un Stream {{domxref("Response")}} jusqu'au bout. Elle retourne une promesse qui s'auto-résout en renvoyant le corps de la requête parsée au format {{jsxref("JSON")}}.

+ +

Syntaxe

+ +
response.json().then(function(data) {
+  // faire quelque chose avec les données
+});
+ +

Paramètres

+ +

Aucun.

+ +

Valeur de retour

+ +

Une promesse résolue contenant le corps de la requête (au format JSON) converti sous la forme d'un objet JavaScript. Cet objet peut correspondre à n'importe quel contenu représentable dans le format JSON -- un objet, un tableau, une chaîne de caractère, un nombre…

+ +

Exemple

+ +

Dans l'exemple fetch json (lancer cet exemple), nous créons une nouvelle requête en utilisant le constructeur {{domxref("Request.Request", "Request()")}}, puis utilisons celle-ci pour récupérer un fichier .json. Lorsque l'appel à fetch réussit, on lit les données et on les parse en utilisant json() pour les convertir en un objet JS, puis enfin on utilise les valeurs de l'objet obtenu pour les insérer dans une liste de noeuds, de manière à afficher nos produits. 

+ +
const myList = document.querySelector('ul');
+const myRequest = new Request('products.json');
+
+fetch(myRequest)
+  .then(response => response.json())
+  .then(data => {
+    for (const product of data.products) {
+      let listItem = document.createElement('li');
+      listItem.appendChild(
+        document.createElement('strong')
+      ).textContent = product.Name;
+      listItem.append(
+        ` can be found in ${
+          product.Location
+        }. Cost: `
+      );
+      listItem.appendChild(
+        document.createElement('strong')
+      ).textContent = `£${product.Price}`;
+      myList.appendChild(listItem);
+    }
+  });
+ +

Spécifications

+ + + + + + + + + + + + + + +
SpécificationStatusComment
{{SpecName('Fetch','#dom-body-json','Body.json()')}}{{Spec2('Fetch')}}Définition initiale
+ +

Compatibilité des navigateurs

+ +

{{Compat("api.Body.json")}}

+ +

Voir aussi

+ + diff --git a/files/fr/web/api/body/index.html b/files/fr/web/api/body/index.html deleted file mode 100644 index 9753edeba3..0000000000 --- a/files/fr/web/api/body/index.html +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Body -slug: Web/API/Body -tags: - - API - - BODY - - Experimental - - Fetch - - Fetch API - - Interface - - Reference - - TopicStub - - request -translation_of: Web/API/Body ---- -
{{ APIRef("Fetch") }}
- -

Le {{glossary("mixin")}} Body de l'API Fetch représente le corps de d'une requête ou d'une réponse, vous permettant de déclarer le type de son contenu et comment le manipuler.

- -

Body est implémenté par {{domxref("Request")}} et {{domxref("Response")}}. Ces derniers fournissent un objet avec un un corps associé (un stream), un drapeaux pour indiquer si le corps a déjà été utilisé (initialisé à faux), et un type MIME (au début, une séquence vide d'octet).

- -

Propriétés

- -
-
{{domxref("Body.body")}} {{readonlyInline}}
-
Un simple getter utilisé pour obtenir un {{domxref("ReadableStream")}} du contenu.
-
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
-
Un {{jsxref("Boolean")}} qui indique si le corps a déjà été lu.
-
- -

Méthodes

- -
-
{{domxref("Body.arrayBuffer()")}}
-
Prend un flux {{domxref("Response")}}, le lit en entier, et le retourne sous forme d'un {{jsxref("ArrayBuffer")}} au travers d'une promesse.
-
{{domxref("Body.blob()")}}
-
Prends un flux {{domxref("Response")}}, le lit en entier, et le retourne dans un {{domxref("Blob")}} au travers d'une promesse.
-
{{domxref("Body.formData()")}}
-
Prends un flux {{domxref("Response")}}, le lit en entier, et le retourne dans un objet {{domxref("FormData")}} au travers d'une promesse.
-
{{domxref("Body.json()")}}
-
Prends un flux {{domxref("Response")}}, le lit en entier et retourne une promesse résolue avec le résultat textuel interprété comme du {{jsxref("JSON")}}.
-
{{domxref("Body.text()")}}
-
Prend un flux {{domxref("Response")}}, le lit en entier, et le retourne dans une {{domxref("USVString")}} (texte) au travers d'une promesse. La réponse est toujours décodée en utilisant l'UTF-8.
-
- -

Exemples

- -

L'exemple suivant utilise un simple appel fetch pour récupérer une image et l'afficher dans un élément {{htmlelement("img")}}. Notez qu'une fois l'image téléchargée, nous devons appeler {{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} implémente body) pour connaître le MIME type correcte.

- -

Code HTML

- -
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
-
- -

Code JavaScript

- -
const myImage = document.querySelector('.my-image');
-fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
-	.then(res => res.blob())
-	.then(res => {
-		const objectURL = URL.createObjectURL(res);
-		myImage.src = objectURL;
-});
- -

{{ EmbedLiveSample('Examples', '100%', '250px') }}

- -

Spécifications

- - - - - - - - - - - - - - -
SpécificationsStatusCommentaire
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}}
- -

Compatibilité des navigateurs

- - - -

{{Compat("api.Body")}}

- -

Voir aussi

- - diff --git a/files/fr/web/api/body/json/index.html b/files/fr/web/api/body/json/index.html deleted file mode 100644 index 121768d6ea..0000000000 --- a/files/fr/web/api/body/json/index.html +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: Body.json() -slug: Web/API/Body/json -tags: - - API - - BODY - - Experimental - - Fetch - - JSON - - Méthode - - Reference -translation_of: Web/API/Body/json ---- -
{{APIRef("Fetch")}}
- -

La méthode json() de {{domxref("Body")}} lit un Stream {{domxref("Response")}} jusqu'au bout. Elle retourne une promesse qui s'auto-résout en renvoyant le corps de la requête parsée au format {{jsxref("JSON")}}.

- -

Syntaxe

- -
response.json().then(function(data) {
-  // faire quelque chose avec les données
-});
- -

Paramètres

- -

Aucun.

- -

Valeur de retour

- -

Une promesse résolue contenant le corps de la requête (au format JSON) converti sous la forme d'un objet JavaScript. Cet objet peut correspondre à n'importe quel contenu représentable dans le format JSON -- un objet, un tableau, une chaîne de caractère, un nombre…

- -

Exemple

- -

Dans l'exemple fetch json (lancer cet exemple), nous créons une nouvelle requête en utilisant le constructeur {{domxref("Request.Request", "Request()")}}, puis utilisons celle-ci pour récupérer un fichier .json. Lorsque l'appel à fetch réussit, on lit les données et on les parse en utilisant json() pour les convertir en un objet JS, puis enfin on utilise les valeurs de l'objet obtenu pour les insérer dans une liste de noeuds, de manière à afficher nos produits. 

- -
const myList = document.querySelector('ul');
-const myRequest = new Request('products.json');
-
-fetch(myRequest)
-  .then(response => response.json())
-  .then(data => {
-    for (const product of data.products) {
-      let listItem = document.createElement('li');
-      listItem.appendChild(
-        document.createElement('strong')
-      ).textContent = product.Name;
-      listItem.append(
-        ` can be found in ${
-          product.Location
-        }. Cost: `
-      );
-      listItem.appendChild(
-        document.createElement('strong')
-      ).textContent = `£${product.Price}`;
-      myList.appendChild(listItem);
-    }
-  });
- -

Spécifications

- - - - - - - - - - - - - - -
SpécificationStatusComment
{{SpecName('Fetch','#dom-body-json','Body.json()')}}{{Spec2('Fetch')}}Définition initiale
- -

Compatibilité des navigateurs

- -

{{Compat("api.Body.json")}}

- -

Voir aussi

- - diff --git a/files/ja/_redirects.txt b/files/ja/_redirects.txt index 8f1da022dc..9561b4b02a 100644 --- a/files/ja/_redirects.txt +++ b/files/ja/_redirects.txt @@ -3717,6 +3717,14 @@ /ja/docs/Web/API/AudioContext/onstatechange /ja/docs/Web/API/BaseAudioContext/onstatechange /ja/docs/Web/API/AudioContext/sampleRate /ja/docs/Web/API/BaseAudioContext/sampleRate /ja/docs/Web/API/AudioContext/state /ja/docs/Web/API/BaseAudioContext/state +/ja/docs/Web/API/Body /ja/docs/orphaned/Web/API/Body +/ja/docs/Web/API/Body/arrayBuffer /ja/docs/orphaned/Web/API/Body/arrayBuffer +/ja/docs/Web/API/Body/blob /ja/docs/orphaned/Web/API/Body/blob +/ja/docs/Web/API/Body/body /ja/docs/orphaned/Web/API/Body/body +/ja/docs/Web/API/Body/bodyUsed /ja/docs/orphaned/Web/API/Body/bodyUsed +/ja/docs/Web/API/Body/formData /ja/docs/orphaned/Web/API/Body/formData +/ja/docs/Web/API/Body/json /ja/docs/orphaned/Web/API/Body/json +/ja/docs/Web/API/Body/text /ja/docs/orphaned/Web/API/Body/text /ja/docs/Web/API/Boolean /ja/docs/Web/JavaScript/Reference/Global_Objects/Boolean /ja/docs/Web/API/CSSMatrix /ja/docs/Web/API/DOMMatrix /ja/docs/Web/API/CSSStyleSheet.insertRule /ja/docs/Web/API/CSSStyleSheet/insertRule diff --git a/files/ja/_wikihistory.json b/files/ja/_wikihistory.json index 95e317b83f..7b31ae8569 100644 --- a/files/ja/_wikihistory.json +++ b/files/ja/_wikihistory.json @@ -10615,72 +10615,6 @@ "YuichiNukiyama" ] }, - "Web/API/Body": { - "modified": "2020-10-15T21:42:48.844Z", - "contributors": [ - "Wind1808", - "dlwe", - "woodmix", - "hamasaki", - "chikoski", - "YuichiNukiyama", - "fscholz" - ] - }, - "Web/API/Body/arrayBuffer": { - "modified": "2020-10-15T21:43:16.481Z", - "contributors": [ - "Wind1808", - "woodmix", - "YuichiNukiyama" - ] - }, - "Web/API/Body/blob": { - "modified": "2020-10-15T21:47:35.044Z", - "contributors": [ - "Wind1808", - "woodmix", - "YuichiNukiyama" - ] - }, - "Web/API/Body/body": { - "modified": "2020-10-15T22:25:57.301Z", - "contributors": [ - "Wind1808" - ] - }, - "Web/API/Body/bodyUsed": { - "modified": "2020-10-15T21:42:42.306Z", - "contributors": [ - "Wind1808", - "YuichiNukiyama" - ] - }, - "Web/API/Body/formData": { - "modified": "2020-10-15T21:43:16.713Z", - "contributors": [ - "Wind1808", - "YuichiNukiyama" - ] - }, - "Web/API/Body/json": { - "modified": "2020-10-15T21:43:16.571Z", - "contributors": [ - "Wind1808", - "mfuji09", - "woodmix", - "YuichiNukiyama" - ] - }, - "Web/API/Body/text": { - "modified": "2020-10-15T21:43:16.444Z", - "contributors": [ - "Wind1808", - "Uemmra3", - "woodmix", - "YuichiNukiyama" - ] - }, "Web/API/BroadcastChannel": { "modified": "2020-10-15T22:19:53.981Z", "contributors": [ @@ -51773,6 +51707,72 @@ "maruhiro" ] }, + "orphaned/Web/API/Body": { + "modified": "2020-10-15T21:42:48.844Z", + "contributors": [ + "Wind1808", + "dlwe", + "woodmix", + "hamasaki", + "chikoski", + "YuichiNukiyama", + "fscholz" + ] + }, + "orphaned/Web/API/Body/arrayBuffer": { + "modified": "2020-10-15T21:43:16.481Z", + "contributors": [ + "Wind1808", + "woodmix", + "YuichiNukiyama" + ] + }, + "orphaned/Web/API/Body/blob": { + "modified": "2020-10-15T21:47:35.044Z", + "contributors": [ + "Wind1808", + "woodmix", + "YuichiNukiyama" + ] + }, + "orphaned/Web/API/Body/body": { + "modified": "2020-10-15T22:25:57.301Z", + "contributors": [ + "Wind1808" + ] + }, + "orphaned/Web/API/Body/bodyUsed": { + "modified": "2020-10-15T21:42:42.306Z", + "contributors": [ + "Wind1808", + "YuichiNukiyama" + ] + }, + "orphaned/Web/API/Body/formData": { + "modified": "2020-10-15T21:43:16.713Z", + "contributors": [ + "Wind1808", + "YuichiNukiyama" + ] + }, + "orphaned/Web/API/Body/json": { + "modified": "2020-10-15T21:43:16.571Z", + "contributors": [ + "Wind1808", + "mfuji09", + "woodmix", + "YuichiNukiyama" + ] + }, + "orphaned/Web/API/Body/text": { + "modified": "2020-10-15T21:43:16.444Z", + "contributors": [ + "Wind1808", + "Uemmra3", + "woodmix", + "YuichiNukiyama" + ] + }, "orphaned/Web/API/ChildNode": { "modified": "2020-11-23T03:36:42.854Z", "contributors": [ diff --git a/files/ja/orphaned/web/api/body/arraybuffer/index.html b/files/ja/orphaned/web/api/body/arraybuffer/index.html new file mode 100644 index 0000000000..ca11540bb0 --- /dev/null +++ b/files/ja/orphaned/web/api/body/arraybuffer/index.html @@ -0,0 +1,109 @@ +--- +title: Body.arrayBuffer() +slug: orphaned/Web/API/Body/arrayBuffer +tags: + - API + - ArrayBuffer + - BODY + - Experimental + - Fetch + - Method + - Reference +translation_of: Web/API/Body/arrayBuffer +original_slug: Web/API/Body/arrayBuffer +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Body")}} ミックスインの arrayBuffer() メソッドは、{{domxref("Response")}} ストリームを取得して、完全に読み取ります。 {{jsxref("ArrayBuffer")}} で解決される promise を返します。

+ +

構文

+ +
response.arrayBuffer().then(function(buffer) {
+  // buffer を使用した何らかの処理
+});
+ +

パラメーター

+ +

なし。

+ +

戻り値

+ +

{{jsxref("ArrayBuffer")}} で解決される promise。

+ +

+ +

音楽の演奏

+ +

fetch array buffer のライブでは、Play ボタンを配置して、押下されると getData() 関数が実行されるようになっています。 再生する前に音声ファイル全体をダウンロードすることに注意してください。 ダウンロード中に演奏を開始したい(つまりストリーム再生したい)なら、次のように {{domxref("HTMLAudioElement")}} を使いましょう。

+ +
new Audio("music.ogg").play();
+
+ +

getData() 関数内では、{{domxref("Request.Request","Request()")}} コンストラクターを使用して新しいリクエストを作成し、それを使用して OGG 音声トラックをフェッチします。 また、{{domxref("AudioContext.createBufferSource")}} を使用して、音声バッファーソースを作成します。 フェッチが成功したら、arrayBuffer() を使用してレスポンスから {{jsxref("ArrayBuffer")}} を読み取り、{{domxref("AudioContext.decodeAudioData")}} を使用して音声データをデコードし、デコードされたデータを音声バッファーソースのバッファー(source.buffer)として設定し、それから {{domxref("AudioContext.destination")}} にソースを接続します。

+ +

getData() の実行が完了すると、start(0) で音声ソースの再生を開始し、それから再生中に再度再生ボタンをクリックできないようにするために(これはしばしばエラーの原因になります)ボタンを無効化しています。

+ +
function getData() {
+  source = audioCtx.createBufferSource();
+
+  var myRequest = new Request('viper.ogg');
+
+  fetch(myRequest).then(function(response) {
+    return response.arrayBuffer();
+  }).then(function(buffer) {
+    audioCtx.decodeAudioData(buffer, function(decodedData) {
+      source.buffer = decodedData;
+      source.connect(audioCtx.destination);
+    });
+  });
+};
+
+// wire up buttons to stop and play audio
+
+play.onclick = function() {
+  getData();
+  source.start(0);
+  play.setAttribute('disabled', 'disabled');
+}
+ +

ファイルを読む

+ +

{{domxref("Response.Response","Response()")}} コンストラクターは、{{domxref("File")}} と {{domxref("Blob")}} を受け入れるため、{{domxref("File")}} を他の形式に読み込むために使用できます。

+ +
function readFile(file) {
+  return new Response(file).arrayBuffer();
+}
+
+ +
<input type="file" onchange="readFile(this.files[0])">
+ +

仕様

+ + + + + + + + + + + + + + +
仕様状態コメント
{{SpecName('Fetch','#dom-body-arraybuffer','arrayBuffer()')}}{{Spec2('Fetch')}}
+ +

ブラウザーの互換性

+ + + +

{{Compat("api.Body.arrayBuffer")}}

+ +

関連情報

+ + diff --git a/files/ja/orphaned/web/api/body/blob/index.html b/files/ja/orphaned/web/api/body/blob/index.html new file mode 100644 index 0000000000..c19d7b7ab5 --- /dev/null +++ b/files/ja/orphaned/web/api/body/blob/index.html @@ -0,0 +1,80 @@ +--- +title: Body.blob() +slug: orphaned/Web/API/Body/blob +tags: + - API + - BODY + - Blob + - Experimental + - Fetch + - Method + - Reference +translation_of: Web/API/Body/blob +original_slug: Web/API/Body/blob +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Body")}} ミックスインの blob() メソッド は、 {{domxref("Response")}} ストリームを取得し、完全に読み込みます。 {{domxref("Blob")}} で解決する promise を返します。

+ +

構文

+ +
response.blob().then(function(myBlob) {
+  // do something with myBlob
+});
+ +

パラメーター

+ +

なし。

+ +
: {{domxref("Response")}} の {{domxref("Response.type")}} が "opaque" の場合、結果の {{domxref("Blob")}} の {{domxref("Blob.size")}} は 0、{{domxref("Blob.type")}} は空の文字列 "" になり、{{domxref("URL.createObjectURL")}} のようなメソッドでは役に立たなくなります。
+ +

戻り値

+ +

{{domxref("Blob")}} で解決する promise。

+ +

+ +

fetch request の例fetch request をライブで実行)では、{{domxref("Request.Request","Request()")}} コンストラクターを使用して新しいリクエストを作成し、それを使用して JPG をフェッチします。 フェッチが成功したら、blob() を使用してレスポンスから {{domxref("Blob")}} を読み取り、それを {{domxref("URL.createObjectURL")}} を使用してオブジェクト URL に入れ、その URL を {{htmlelement("img")}} 要素のソースとして設定して画像を表示します。

+ +
var myImage = document.querySelector('img');
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest)
+.then(response => response.blob())
+.then(function(myBlob) {
+  var objectURL = URL.createObjectURL(myBlob);
+  myImage.src = objectURL;
+});
+
+ +

仕様

+ + + + + + + + + + + + + + +
仕様状態コメント
{{SpecName('Fetch','#dom-body-blob','blob()')}}{{Spec2('Fetch')}}
+ +

ブラウザーの互換性

+ + + +

{{Compat("api.Body.blob")}}

+ +

関連情報

+ + diff --git a/files/ja/orphaned/web/api/body/body/index.html b/files/ja/orphaned/web/api/body/body/index.html new file mode 100644 index 0000000000..2b5cf02536 --- /dev/null +++ b/files/ja/orphaned/web/api/body/body/index.html @@ -0,0 +1,95 @@ +--- +title: Body.body +slug: orphaned/Web/API/Body/body +tags: + - API + - BODY + - Experimental + - Fetch + - Property + - Reference + - Streams +translation_of: Web/API/Body/body +original_slug: Web/API/Body/body +--- +
{{APIRef("Fetch")}}{{seecompattable}}
+ +

{{domxref("Body")}} ミックスインの body 読み取り専用プロパティは、ボディコンテンツの {{domxref("ReadableStream")}} を公開するために使用する単純なゲッターです。

+ +

構文

+ +
var stream = response.body;
+ +

+ +

{{domxref("ReadableStream")}}。

+ +

+ +

単純なストリームポンプの例では、画像をフェッチし、response.body を使用してレスポンスのストリームを公開し、{{domxref("ReadableStream.getReader()", "ReadableStream.getReader()")}} を使用してリーダーを作成し、そのストリームのチャンクを2番目のカスタム読み取り可能なストリームのキューに入れます — 画像の同一コピーを効果的に作成します。

+ +
const image = document.getElementById('target');
+
+// 元の画像をフェッチ
+fetch('./tortoise.png')
+// その body を ReadableStream として取得
+.then(response => response.body)
+.then(body => {
+  const reader = body.getReader();
+
+  return new ReadableStream({
+    start(controller) {
+      return pump();
+
+      function pump() {
+        return reader.read().then(({ done, value }) => {
+          // データを消費する必要がなくなったら、ストリームを閉じます
+          if (done) {
+            controller.close();
+            return;
+          }
+
+          // 次のデータチャンクを対象のストリームのキューに入れます
+          controller.enqueue(value);
+          return pump();
+        });
+      }
+    }
+  })
+})
+.then(stream => new Response(stream))
+.then(response => response.blob())
+.then(blob => URL.createObjectURL(blob))
+.then(url => console.log(image.src = url))
+.catch(err => console.error(err));
+ +

仕様

+ + + + + + + + + + + + + + +
仕様状態コメント
{{SpecName('Fetch','#dom-body-body','body')}}{{Spec2('Fetch')}}
+ +

ブラウザーの互換性

+ + + +

{{Compat("api.Body.body")}}

+ +

関連情報

+ + diff --git a/files/ja/orphaned/web/api/body/bodyused/index.html b/files/ja/orphaned/web/api/body/bodyused/index.html new file mode 100644 index 0000000000..6a785cbf9a --- /dev/null +++ b/files/ja/orphaned/web/api/body/bodyused/index.html @@ -0,0 +1,82 @@ +--- +title: Body.bodyUsed +slug: orphaned/Web/API/Body/bodyUsed +tags: + - API + - BODY + - Experimental + - Fetch + - Property + - Reference + - bodyUsed +translation_of: Web/API/Body/bodyUsed +original_slug: Web/API/Body/bodyUsed +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Body")}} ミックスインの bodyUsed 読み取り専用プロパティは、ボディが既に読み取られたかどうかを示す {{jsxref("Boolean")}} 値を含みます。

+ +

構文

+ +
var myBodyUsed = response.bodyUsed;
+ +

+ +

{{jsxref("Boolean")}} 値。

+ +

+ +

Fetch Request の例Fetch Request をライブで実行)では、{{domxref("Request.Request","Request()")}} コンストラクターを使用して新しいリクエストを作成し、それを使用して JPG をフェッチします。 フェッチが成功したら、blob() を使用してレスポンスから {{domxref("Blob")}} を読み取り、{{domxref("URL.createObjectURL")}} を使用してオブジェクト URL に格納し、その URL を {{htmlelement("img")}} 要素のソースとして設定して画像を表示します。

+ +

response.blob() の呼び出し前後に、response.bodyUsed をコンソールに記録していることに注目してください。 その時点でボディが読み取られたかによるため、これは呼び出し前では false を返し、その後では true を返します。

+ +

HTML の内容

+ +
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
+
+ +

JS の内容

+ +
var myImage = document.querySelector('.my-image');
+fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg').then(function(response) {
+    console.log(response.bodyUsed);
+    var res = response.blob();
+    console.log(response.bodyUsed);
+    return res;
+}).then(function(response) {
+    var objectURL = URL.createObjectURL(response);
+    myImage.src = objectURL;
+});
+ +

{{ EmbedLiveSample('Example', '100%', '250px') }}

+ +

仕様

+ + + + + + + + + + + + + + +
仕様状態コメント
{{SpecName('Fetch','#dom-body-bodyused','bodyUsed')}}{{Spec2('Fetch')}}
+ +

ブラウザーの互換性

+ + + +

{{Compat("api.Body.bodyUsed")}}

+ +

関連情報

+ + diff --git a/files/ja/orphaned/web/api/body/formdata/index.html b/files/ja/orphaned/web/api/body/formdata/index.html new file mode 100644 index 0000000000..922fd2986d --- /dev/null +++ b/files/ja/orphaned/web/api/body/formdata/index.html @@ -0,0 +1,73 @@ +--- +title: Body.formData() +slug: orphaned/Web/API/Body/formData +tags: + - API + - BODY + - Experimenal + - Fetch + - Fetch API + - FormData + - Method + - NeedsExample + - Reference +translation_of: Web/API/Body/formData +original_slug: Web/API/Body/formData +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Body")}} ミックスインの formData() メソッドは、{{domxref("Response")}} ストリームを取得して、完全に読み取ります。 {{domxref("FormData")}} オブジェクトで解決される promise を返します。

+ +
+

: これは主に service worker に関連しています。 ユーザーがフォームを送信し、service worker がリクエストをインターセプトした場合を考えてみましょう。 例えば、key-value マップを取得するために formData() を呼び出し、いくつかのフィールドを修正した後、フォームをサーバ側に送信できます(またはローカルで使用できます)。

+
+ +

構文

+ +
response.formData()
+.then(function(formdata) {
+  // formdata を使った何らかの処理
+});
+ +

パラメーター

+ +

なし。

+ +

戻り値

+ +

{{domxref("FormData")}} オブジェクトで解決される {{jsxref("Promise")}}。

+ +

+ +

TBD.

+ +

仕様

+ + + + + + + + + + + + + + +
仕様状態コメント
{{SpecName('Fetch','#dom-body-formdata','formData()')}}{{Spec2('Fetch')}}
+ +

ブラウザーの互換性

+ + + +

{{Compat("api.Body.formData")}}

+ +

関連情報

+ + diff --git a/files/ja/orphaned/web/api/body/index.html b/files/ja/orphaned/web/api/body/index.html new file mode 100644 index 0000000000..01ff7c7dea --- /dev/null +++ b/files/ja/orphaned/web/api/body/index.html @@ -0,0 +1,96 @@ +--- +title: Body +slug: orphaned/Web/API/Body +tags: + - API + - BODY + - Experimental + - Fetch + - Fetch API + - Interface + - Reference + - request +translation_of: Web/API/Body +original_slug: Web/API/Body +--- +
{{ APIRef("Fetch") }}
+ +

Fetch APIBody {{glossary("mixin","ミックスイン")}}は、リクエスト/レスポンスのボディを表し、そのコンテンツタイプが何であるかとその処理方法を宣言できます。

+ +

Body は {{domxref("Request")}} と {{domxref("Response")}} の両方で実装されます。 これにより、これらのオブジェクトに、関連するボディ(ストリーム)と使用済みフラグ(初期は未設定)、MIME タイプ(初期は空のバイトシーケンス)が提供されます。(訳注:コンテンツタイプ(MIME タイプ)は、{{domxref("Headers")}} の "Content-Type" にあります。 でも、例を見てもわかる通り、普通はリクエストの時点で決定しているので、これを調べてはいません。)

+ +

プロパティ

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
ボディコンテンツの {{domxref("ReadableStream")}} を公開するために使用する単純なゲッター。
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
既にボディが読み込まれたかどうかを示す {{jsxref("Boolean")}} 値。
+
+ +

メソッド

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
{{domxref("Response")}} ストリームを取得し、完全に読み込む。 {{jsxref("ArrayBuffer")}} で解決する promise を返す。
+
{{domxref("Body.blob()")}}
+
{{domxref("Response")}} ストリームを取得し、完全に読み込む。 {{domxref("Blob")}} で解決する promise を返す。
+
{{domxref("Body.formData()")}}
+
{{domxref("Response")}} ストリームを取得し、完全に読み込む。 {{domxref("FormData")}} オブジェクトで解決する promise を返す。
+
{{domxref("Body.json()")}}
+
{{domxref("Response")}} ストリームを取得し、完全に読み込む。 ボディのテキストを {{jsxref("JSON")}} として解析した結果で解決する promise を返す。
+
{{domxref("Body.text()")}}
+
{{domxref("Response")}} ストリームを取得し、完全に読み込む。 {{domxref("USVString")}}(テキスト)で解決する promise を返す。 レスポンスは常に UTF-8 でデコードする。
+
+ +

+ +

次の例では、単純なフェッチ呼び出しを使用して画像を取得し、{{htmlelement("img")}} タグで表示します。 画像をリクエストしているので、{{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} は Body を実装しています)を実行して、レスポンスに正しい MIME タイプを与える必要があることに注意してください。

+ +

HTML の内容

+ +
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
+
+ +

JS の内容

+ +
const myImage = document.querySelector('.my-image');
+fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
+	.then(res => res.blob())
+	.then(res => {
+		const objectURL = URL.createObjectURL(res);
+		myImage.src = objectURL;
+});
+ +

{{ EmbedLiveSample('Examples', '100%', '250px') }}

+ +

仕様

+ + + + + + + + + + + + + + +
仕様状態コメント
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}}
+ +

ブラウザーの互換性

+ + + +

{{Compat("api.Body")}}

+ +

関連情報

+ + diff --git a/files/ja/orphaned/web/api/body/json/index.html b/files/ja/orphaned/web/api/body/json/index.html new file mode 100644 index 0000000000..3ee9cd7c6d --- /dev/null +++ b/files/ja/orphaned/web/api/body/json/index.html @@ -0,0 +1,92 @@ +--- +title: Body.json() +slug: orphaned/Web/API/Body/json +tags: + - API + - BODY + - Experimental + - Fetch + - JSON + - Method + - Reference + - メソッド +translation_of: Web/API/Body/json +original_slug: Web/API/Body/json +--- +
{{APIRef("Fetch API")}}
+ +

{{DOMxRef("Body")}} ミックスインの json() メソッドは、 {{DOMxRef("Response")}} ストリームを取得して、完全に読み取ります。 ボディのテキストを {{JSxRef("JSON")}} として解釈した結果で解決する promise を返します。

+ +

構文

+ +
response.json().then(data => {
+  // data を使用した処理を実行する
+});
+ +

パラメーター

+ +

なし。

+ +

戻り値

+ +

JavaScript オブジェクトに解決される {{jsxref("Promise")}}。 このオブジェクトは、オブジェクト、配列、文字列、数値など、JSON で表現できるものであれば何でもなります。

+ +

+ +

fetch json の例fetch json をライブで実行)では、 {{DOMxRef("Request.Request", "Request()")}} コンストラクターを使用して新しいリクエストを作成し、それを使用して .json ファイルをフェッチします。 フェッチが成功したら、json() を使用してデータを読み取り、解析し、結果のオブジェクトから期待通りに値を読みだし、それらの値をリスト項目に追加して商品データとして表示します。

+ +
const myList = document.querySelector('ul');
+const myRequest = new Request('products.json');
+
+fetch(myRequest)
+  .then(response => response.json())
+  .then(data => {
+    for (const product of data.products) {
+      let listItem = document.createElement('li');
+      listItem.appendChild(
+        document.createElement('strong')
+      ).textContent = product.Name;
+      listItem.append(
+        ` can be found in ${
+          product.Location
+        }. Cost: `
+      );
+      listItem.appendChild(
+        document.createElement('strong')
+      ).textContent = `£${product.Price}`;
+      myList.appendChild(listItem);
+    }
+  });
+ +

仕様

+ + + + + + + + + + + + + + + + +
仕様状態コメント
{{SpecName("Fetch", "#dom-body-json", "Body.json()")}}{{Spec2("Fetch")}}初期定義
+ +

ブラウザーの互換性

+ + + +

{{Compat("api.Body.json")}}

+ +

関連情報

+ + diff --git a/files/ja/orphaned/web/api/body/text/index.html b/files/ja/orphaned/web/api/body/text/index.html new file mode 100644 index 0000000000..9e66199603 --- /dev/null +++ b/files/ja/orphaned/web/api/body/text/index.html @@ -0,0 +1,89 @@ +--- +title: Body.text() +slug: orphaned/Web/API/Body/text +tags: + - API + - BODY + - Experimental + - Fetch + - Method + - Reference + - Text +translation_of: Web/API/Body/text +original_slug: Web/API/Body/text +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Body")}} ミックスインの text() メソッドは、{{domxref("Response")}} ストリームを取得し、完全に読み込みます。 {{domxref("USVString")}} オブジェクト(テキスト)で解決する promise を返します。 レスポンスは常に UTF-8 としてデコードします。

+ +

構文

+ +
response.text().then(function (text) {
+  // text レスポンスを使用して何か実行する。
+});
+ +

パラメーター

+ +

なし。

+ +

戻り値

+ +

{{domxref("USVString")}} で解決する promise。

+ +

+ +

fetch text の例fetch text をライブで実行)には、{{htmlelement("article")}} 要素と 3 つのリンク(myLinks 配列に格納されています)があります。 最初に、リンクのすべてをループし、それぞれのリンクに、その 1 つをクリックしたとき、リンクの data-page 識別子を引数として渡して getData() 関数が実行されるように、onclick イベントハンドラーを設定します。

+ +

getData() が実行されると、{{domxref("Request.Request","Request()")}} コンストラクターを使用して新しいリクエストを作成し、それを使用して特定の .txt ファイルをフェッチします。 フェッチが成功したら、text() を使用してレスポンスから {{jsxref("USVString")}}(テキスト)オブジェクトを読み取り、{{htmlelement("article")}} 要素の {{domxref("Element.innerHTML","innerHTML")}} にテキストオブジェクトの値を設定します。

+ +
var myArticle = document.querySelector('article');
+var myLinks = document.querySelectorAll('ul a');
+
+for(i = 0; i <= myLinks.length-1; i++) {
+  myLinks[i].onclick = function(e) {
+    e.preventDefault();
+    var linkData = e.target.getAttribute('data-page');
+    getData(linkData);
+  }
+};
+
+function getData(pageId) {
+  console.log(pageId);
+  var myRequest = new Request(pageId + '.txt');
+  fetch(myRequest).then(function(response) {
+    return response.text().then(function(text) {
+      myArticle.innerHTML = text;
+    });
+  });
+}
+ +

仕様

+ + + + + + + + + + + + + + +
仕様状態コメント
{{SpecName('Fetch','#dom-body-text','text()')}}{{Spec2('Fetch')}}
+ +

ブラウザーの互換性

+ + + +

{{Compat("api.Body.text")}}

+ +

関連情報

+ + diff --git a/files/ja/web/api/body/arraybuffer/index.html b/files/ja/web/api/body/arraybuffer/index.html deleted file mode 100644 index 2cbc474ddc..0000000000 --- a/files/ja/web/api/body/arraybuffer/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: Body.arrayBuffer() -slug: Web/API/Body/arrayBuffer -tags: - - API - - ArrayBuffer - - BODY - - Experimental - - Fetch - - Method - - Reference -translation_of: Web/API/Body/arrayBuffer ---- -
{{APIRef("Fetch")}}
- -

{{domxref("Body")}} ミックスインの arrayBuffer() メソッドは、{{domxref("Response")}} ストリームを取得して、完全に読み取ります。 {{jsxref("ArrayBuffer")}} で解決される promise を返します。

- -

構文

- -
response.arrayBuffer().then(function(buffer) {
-  // buffer を使用した何らかの処理
-});
- -

パラメーター

- -

なし。

- -

戻り値

- -

{{jsxref("ArrayBuffer")}} で解決される promise。

- -

- -

音楽の演奏

- -

fetch array buffer のライブでは、Play ボタンを配置して、押下されると getData() 関数が実行されるようになっています。 再生する前に音声ファイル全体をダウンロードすることに注意してください。 ダウンロード中に演奏を開始したい(つまりストリーム再生したい)なら、次のように {{domxref("HTMLAudioElement")}} を使いましょう。

- -
new Audio("music.ogg").play();
-
- -

getData() 関数内では、{{domxref("Request.Request","Request()")}} コンストラクターを使用して新しいリクエストを作成し、それを使用して OGG 音声トラックをフェッチします。 また、{{domxref("AudioContext.createBufferSource")}} を使用して、音声バッファーソースを作成します。 フェッチが成功したら、arrayBuffer() を使用してレスポンスから {{jsxref("ArrayBuffer")}} を読み取り、{{domxref("AudioContext.decodeAudioData")}} を使用して音声データをデコードし、デコードされたデータを音声バッファーソースのバッファー(source.buffer)として設定し、それから {{domxref("AudioContext.destination")}} にソースを接続します。

- -

getData() の実行が完了すると、start(0) で音声ソースの再生を開始し、それから再生中に再度再生ボタンをクリックできないようにするために(これはしばしばエラーの原因になります)ボタンを無効化しています。

- -
function getData() {
-  source = audioCtx.createBufferSource();
-
-  var myRequest = new Request('viper.ogg');
-
-  fetch(myRequest).then(function(response) {
-    return response.arrayBuffer();
-  }).then(function(buffer) {
-    audioCtx.decodeAudioData(buffer, function(decodedData) {
-      source.buffer = decodedData;
-      source.connect(audioCtx.destination);
-    });
-  });
-};
-
-// wire up buttons to stop and play audio
-
-play.onclick = function() {
-  getData();
-  source.start(0);
-  play.setAttribute('disabled', 'disabled');
-}
- -

ファイルを読む

- -

{{domxref("Response.Response","Response()")}} コンストラクターは、{{domxref("File")}} と {{domxref("Blob")}} を受け入れるため、{{domxref("File")}} を他の形式に読み込むために使用できます。

- -
function readFile(file) {
-  return new Response(file).arrayBuffer();
-}
-
- -
<input type="file" onchange="readFile(this.files[0])">
- -

仕様

- - - - - - - - - - - - - - -
仕様状態コメント
{{SpecName('Fetch','#dom-body-arraybuffer','arrayBuffer()')}}{{Spec2('Fetch')}}
- -

ブラウザーの互換性

- - - -

{{Compat("api.Body.arrayBuffer")}}

- -

関連情報

- - diff --git a/files/ja/web/api/body/blob/index.html b/files/ja/web/api/body/blob/index.html deleted file mode 100644 index 1fb7cf8bbe..0000000000 --- a/files/ja/web/api/body/blob/index.html +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: Body.blob() -slug: Web/API/Body/blob -tags: - - API - - BODY - - Blob - - Experimental - - Fetch - - Method - - Reference -translation_of: Web/API/Body/blob ---- -
{{APIRef("Fetch")}}
- -

{{domxref("Body")}} ミックスインの blob() メソッド は、 {{domxref("Response")}} ストリームを取得し、完全に読み込みます。 {{domxref("Blob")}} で解決する promise を返します。

- -

構文

- -
response.blob().then(function(myBlob) {
-  // do something with myBlob
-});
- -

パラメーター

- -

なし。

- -
: {{domxref("Response")}} の {{domxref("Response.type")}} が "opaque" の場合、結果の {{domxref("Blob")}} の {{domxref("Blob.size")}} は 0、{{domxref("Blob.type")}} は空の文字列 "" になり、{{domxref("URL.createObjectURL")}} のようなメソッドでは役に立たなくなります。
- -

戻り値

- -

{{domxref("Blob")}} で解決する promise。

- -

- -

fetch request の例fetch request をライブで実行)では、{{domxref("Request.Request","Request()")}} コンストラクターを使用して新しいリクエストを作成し、それを使用して JPG をフェッチします。 フェッチが成功したら、blob() を使用してレスポンスから {{domxref("Blob")}} を読み取り、それを {{domxref("URL.createObjectURL")}} を使用してオブジェクト URL に入れ、その URL を {{htmlelement("img")}} 要素のソースとして設定して画像を表示します。

- -
var myImage = document.querySelector('img');
-
-var myRequest = new Request('flowers.jpg');
-
-fetch(myRequest)
-.then(response => response.blob())
-.then(function(myBlob) {
-  var objectURL = URL.createObjectURL(myBlob);
-  myImage.src = objectURL;
-});
-
- -

仕様

- - - - - - - - - - - - - - -
仕様状態コメント
{{SpecName('Fetch','#dom-body-blob','blob()')}}{{Spec2('Fetch')}}
- -

ブラウザーの互換性

- - - -

{{Compat("api.Body.blob")}}

- -

関連情報

- - diff --git a/files/ja/web/api/body/body/index.html b/files/ja/web/api/body/body/index.html deleted file mode 100644 index fb966a5fe2..0000000000 --- a/files/ja/web/api/body/body/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Body.body -slug: Web/API/Body/body -tags: - - API - - BODY - - Experimental - - Fetch - - Property - - Reference - - Streams -translation_of: Web/API/Body/body ---- -
{{APIRef("Fetch")}}{{seecompattable}}
- -

{{domxref("Body")}} ミックスインの body 読み取り専用プロパティは、ボディコンテンツの {{domxref("ReadableStream")}} を公開するために使用する単純なゲッターです。

- -

構文

- -
var stream = response.body;
- -

- -

{{domxref("ReadableStream")}}。

- -

- -

単純なストリームポンプの例では、画像をフェッチし、response.body を使用してレスポンスのストリームを公開し、{{domxref("ReadableStream.getReader()", "ReadableStream.getReader()")}} を使用してリーダーを作成し、そのストリームのチャンクを2番目のカスタム読み取り可能なストリームのキューに入れます — 画像の同一コピーを効果的に作成します。

- -
const image = document.getElementById('target');
-
-// 元の画像をフェッチ
-fetch('./tortoise.png')
-// その body を ReadableStream として取得
-.then(response => response.body)
-.then(body => {
-  const reader = body.getReader();
-
-  return new ReadableStream({
-    start(controller) {
-      return pump();
-
-      function pump() {
-        return reader.read().then(({ done, value }) => {
-          // データを消費する必要がなくなったら、ストリームを閉じます
-          if (done) {
-            controller.close();
-            return;
-          }
-
-          // 次のデータチャンクを対象のストリームのキューに入れます
-          controller.enqueue(value);
-          return pump();
-        });
-      }
-    }
-  })
-})
-.then(stream => new Response(stream))
-.then(response => response.blob())
-.then(blob => URL.createObjectURL(blob))
-.then(url => console.log(image.src = url))
-.catch(err => console.error(err));
- -

仕様

- - - - - - - - - - - - - - -
仕様状態コメント
{{SpecName('Fetch','#dom-body-body','body')}}{{Spec2('Fetch')}}
- -

ブラウザーの互換性

- - - -

{{Compat("api.Body.body")}}

- -

関連情報

- - diff --git a/files/ja/web/api/body/bodyused/index.html b/files/ja/web/api/body/bodyused/index.html deleted file mode 100644 index 2c51ec65f4..0000000000 --- a/files/ja/web/api/body/bodyused/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Body.bodyUsed -slug: Web/API/Body/bodyUsed -tags: - - API - - BODY - - Experimental - - Fetch - - Property - - Reference - - bodyUsed -translation_of: Web/API/Body/bodyUsed ---- -
{{APIRef("Fetch")}}
- -

{{domxref("Body")}} ミックスインの bodyUsed 読み取り専用プロパティは、ボディが既に読み取られたかどうかを示す {{jsxref("Boolean")}} 値を含みます。

- -

構文

- -
var myBodyUsed = response.bodyUsed;
- -

- -

{{jsxref("Boolean")}} 値。

- -

- -

Fetch Request の例Fetch Request をライブで実行)では、{{domxref("Request.Request","Request()")}} コンストラクターを使用して新しいリクエストを作成し、それを使用して JPG をフェッチします。 フェッチが成功したら、blob() を使用してレスポンスから {{domxref("Blob")}} を読み取り、{{domxref("URL.createObjectURL")}} を使用してオブジェクト URL に格納し、その URL を {{htmlelement("img")}} 要素のソースとして設定して画像を表示します。

- -

response.blob() の呼び出し前後に、response.bodyUsed をコンソールに記録していることに注目してください。 その時点でボディが読み取られたかによるため、これは呼び出し前では false を返し、その後では true を返します。

- -

HTML の内容

- -
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
-
- -

JS の内容

- -
var myImage = document.querySelector('.my-image');
-fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg').then(function(response) {
-    console.log(response.bodyUsed);
-    var res = response.blob();
-    console.log(response.bodyUsed);
-    return res;
-}).then(function(response) {
-    var objectURL = URL.createObjectURL(response);
-    myImage.src = objectURL;
-});
- -

{{ EmbedLiveSample('Example', '100%', '250px') }}

- -

仕様

- - - - - - - - - - - - - - -
仕様状態コメント
{{SpecName('Fetch','#dom-body-bodyused','bodyUsed')}}{{Spec2('Fetch')}}
- -

ブラウザーの互換性

- - - -

{{Compat("api.Body.bodyUsed")}}

- -

関連情報

- - diff --git a/files/ja/web/api/body/formdata/index.html b/files/ja/web/api/body/formdata/index.html deleted file mode 100644 index 4826d0faa7..0000000000 --- a/files/ja/web/api/body/formdata/index.html +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Body.formData() -slug: Web/API/Body/formData -tags: - - API - - BODY - - Experimenal - - Fetch - - Fetch API - - FormData - - Method - - NeedsExample - - Reference -translation_of: Web/API/Body/formData ---- -
{{APIRef("Fetch")}}
- -

{{domxref("Body")}} ミックスインの formData() メソッドは、{{domxref("Response")}} ストリームを取得して、完全に読み取ります。 {{domxref("FormData")}} オブジェクトで解決される promise を返します。

- -
-

: これは主に service worker に関連しています。 ユーザーがフォームを送信し、service worker がリクエストをインターセプトした場合を考えてみましょう。 例えば、key-value マップを取得するために formData() を呼び出し、いくつかのフィールドを修正した後、フォームをサーバ側に送信できます(またはローカルで使用できます)。

-
- -

構文

- -
response.formData()
-.then(function(formdata) {
-  // formdata を使った何らかの処理
-});
- -

パラメーター

- -

なし。

- -

戻り値

- -

{{domxref("FormData")}} オブジェクトで解決される {{jsxref("Promise")}}。

- -

- -

TBD.

- -

仕様

- - - - - - - - - - - - - - -
仕様状態コメント
{{SpecName('Fetch','#dom-body-formdata','formData()')}}{{Spec2('Fetch')}}
- -

ブラウザーの互換性

- - - -

{{Compat("api.Body.formData")}}

- -

関連情報

- - diff --git a/files/ja/web/api/body/index.html b/files/ja/web/api/body/index.html deleted file mode 100644 index 271bc73453..0000000000 --- a/files/ja/web/api/body/index.html +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: Body -slug: Web/API/Body -tags: - - API - - BODY - - Experimental - - Fetch - - Fetch API - - Interface - - Reference - - request -translation_of: Web/API/Body ---- -
{{ APIRef("Fetch") }}
- -

Fetch APIBody {{glossary("mixin","ミックスイン")}}は、リクエスト/レスポンスのボディを表し、そのコンテンツタイプが何であるかとその処理方法を宣言できます。

- -

Body は {{domxref("Request")}} と {{domxref("Response")}} の両方で実装されます。 これにより、これらのオブジェクトに、関連するボディ(ストリーム)と使用済みフラグ(初期は未設定)、MIME タイプ(初期は空のバイトシーケンス)が提供されます。(訳注:コンテンツタイプ(MIME タイプ)は、{{domxref("Headers")}} の "Content-Type" にあります。 でも、例を見てもわかる通り、普通はリクエストの時点で決定しているので、これを調べてはいません。)

- -

プロパティ

- -
-
{{domxref("Body.body")}} {{readonlyInline}}
-
ボディコンテンツの {{domxref("ReadableStream")}} を公開するために使用する単純なゲッター。
-
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
-
既にボディが読み込まれたかどうかを示す {{jsxref("Boolean")}} 値。
-
- -

メソッド

- -
-
{{domxref("Body.arrayBuffer()")}}
-
{{domxref("Response")}} ストリームを取得し、完全に読み込む。 {{jsxref("ArrayBuffer")}} で解決する promise を返す。
-
{{domxref("Body.blob()")}}
-
{{domxref("Response")}} ストリームを取得し、完全に読み込む。 {{domxref("Blob")}} で解決する promise を返す。
-
{{domxref("Body.formData()")}}
-
{{domxref("Response")}} ストリームを取得し、完全に読み込む。 {{domxref("FormData")}} オブジェクトで解決する promise を返す。
-
{{domxref("Body.json()")}}
-
{{domxref("Response")}} ストリームを取得し、完全に読み込む。 ボディのテキストを {{jsxref("JSON")}} として解析した結果で解決する promise を返す。
-
{{domxref("Body.text()")}}
-
{{domxref("Response")}} ストリームを取得し、完全に読み込む。 {{domxref("USVString")}}(テキスト)で解決する promise を返す。 レスポンスは常に UTF-8 でデコードする。
-
- -

- -

次の例では、単純なフェッチ呼び出しを使用して画像を取得し、{{htmlelement("img")}} タグで表示します。 画像をリクエストしているので、{{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} は Body を実装しています)を実行して、レスポンスに正しい MIME タイプを与える必要があることに注意してください。

- -

HTML の内容

- -
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
-
- -

JS の内容

- -
const myImage = document.querySelector('.my-image');
-fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
-	.then(res => res.blob())
-	.then(res => {
-		const objectURL = URL.createObjectURL(res);
-		myImage.src = objectURL;
-});
- -

{{ EmbedLiveSample('Examples', '100%', '250px') }}

- -

仕様

- - - - - - - - - - - - - - -
仕様状態コメント
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}}
- -

ブラウザーの互換性

- - - -

{{Compat("api.Body")}}

- -

関連情報

- - diff --git a/files/ja/web/api/body/json/index.html b/files/ja/web/api/body/json/index.html deleted file mode 100644 index 5d470651c4..0000000000 --- a/files/ja/web/api/body/json/index.html +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: Body.json() -slug: Web/API/Body/json -tags: - - API - - BODY - - Experimental - - Fetch - - JSON - - Method - - Reference - - メソッド -translation_of: Web/API/Body/json ---- -
{{APIRef("Fetch API")}}
- -

{{DOMxRef("Body")}} ミックスインの json() メソッドは、 {{DOMxRef("Response")}} ストリームを取得して、完全に読み取ります。 ボディのテキストを {{JSxRef("JSON")}} として解釈した結果で解決する promise を返します。

- -

構文

- -
response.json().then(data => {
-  // data を使用した処理を実行する
-});
- -

パラメーター

- -

なし。

- -

戻り値

- -

JavaScript オブジェクトに解決される {{jsxref("Promise")}}。 このオブジェクトは、オブジェクト、配列、文字列、数値など、JSON で表現できるものであれば何でもなります。

- -

- -

fetch json の例fetch json をライブで実行)では、 {{DOMxRef("Request.Request", "Request()")}} コンストラクターを使用して新しいリクエストを作成し、それを使用して .json ファイルをフェッチします。 フェッチが成功したら、json() を使用してデータを読み取り、解析し、結果のオブジェクトから期待通りに値を読みだし、それらの値をリスト項目に追加して商品データとして表示します。

- -
const myList = document.querySelector('ul');
-const myRequest = new Request('products.json');
-
-fetch(myRequest)
-  .then(response => response.json())
-  .then(data => {
-    for (const product of data.products) {
-      let listItem = document.createElement('li');
-      listItem.appendChild(
-        document.createElement('strong')
-      ).textContent = product.Name;
-      listItem.append(
-        ` can be found in ${
-          product.Location
-        }. Cost: `
-      );
-      listItem.appendChild(
-        document.createElement('strong')
-      ).textContent = `£${product.Price}`;
-      myList.appendChild(listItem);
-    }
-  });
- -

仕様

- - - - - - - - - - - - - - - - -
仕様状態コメント
{{SpecName("Fetch", "#dom-body-json", "Body.json()")}}{{Spec2("Fetch")}}初期定義
- -

ブラウザーの互換性

- - - -

{{Compat("api.Body.json")}}

- -

関連情報

- - diff --git a/files/ja/web/api/body/text/index.html b/files/ja/web/api/body/text/index.html deleted file mode 100644 index d39fb14d9c..0000000000 --- a/files/ja/web/api/body/text/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Body.text() -slug: Web/API/Body/text -tags: - - API - - BODY - - Experimental - - Fetch - - Method - - Reference - - Text -translation_of: Web/API/Body/text ---- -
{{APIRef("Fetch")}}
- -

{{domxref("Body")}} ミックスインの text() メソッドは、{{domxref("Response")}} ストリームを取得し、完全に読み込みます。 {{domxref("USVString")}} オブジェクト(テキスト)で解決する promise を返します。 レスポンスは常に UTF-8 としてデコードします。

- -

構文

- -
response.text().then(function (text) {
-  // text レスポンスを使用して何か実行する。
-});
- -

パラメーター

- -

なし。

- -

戻り値

- -

{{domxref("USVString")}} で解決する promise。

- -

- -

fetch text の例fetch text をライブで実行)には、{{htmlelement("article")}} 要素と 3 つのリンク(myLinks 配列に格納されています)があります。 最初に、リンクのすべてをループし、それぞれのリンクに、その 1 つをクリックしたとき、リンクの data-page 識別子を引数として渡して getData() 関数が実行されるように、onclick イベントハンドラーを設定します。

- -

getData() が実行されると、{{domxref("Request.Request","Request()")}} コンストラクターを使用して新しいリクエストを作成し、それを使用して特定の .txt ファイルをフェッチします。 フェッチが成功したら、text() を使用してレスポンスから {{jsxref("USVString")}}(テキスト)オブジェクトを読み取り、{{htmlelement("article")}} 要素の {{domxref("Element.innerHTML","innerHTML")}} にテキストオブジェクトの値を設定します。

- -
var myArticle = document.querySelector('article');
-var myLinks = document.querySelectorAll('ul a');
-
-for(i = 0; i <= myLinks.length-1; i++) {
-  myLinks[i].onclick = function(e) {
-    e.preventDefault();
-    var linkData = e.target.getAttribute('data-page');
-    getData(linkData);
-  }
-};
-
-function getData(pageId) {
-  console.log(pageId);
-  var myRequest = new Request(pageId + '.txt');
-  fetch(myRequest).then(function(response) {
-    return response.text().then(function(text) {
-      myArticle.innerHTML = text;
-    });
-  });
-}
- -

仕様

- - - - - - - - - - - - - - -
仕様状態コメント
{{SpecName('Fetch','#dom-body-text','text()')}}{{Spec2('Fetch')}}
- -

ブラウザーの互換性

- - - -

{{Compat("api.Body.text")}}

- -

関連情報

- - diff --git a/files/ko/_redirects.txt b/files/ko/_redirects.txt index 3afeb95864..ae45ac6504 100644 --- a/files/ko/_redirects.txt +++ b/files/ko/_redirects.txt @@ -595,6 +595,8 @@ /ko/docs/Using_the_Mozilla_JavaScript_interface_to_XSL_Transformations /ko/docs/Web/XSLT/Using_the_Mozilla_JavaScript_interface_to_XSL_Transformations /ko/docs/Web/API/AbstractWorker /ko/docs/orphaned/Web/API/AbstractWorker /ko/docs/Web/API/Ambient_Light_Events /ko/docs/orphaned/Web/API/Ambient_Light_Events +/ko/docs/Web/API/Body /ko/docs/orphaned/Web/API/Body +/ko/docs/Web/API/Body/json /ko/docs/orphaned/Web/API/Body/json /ko/docs/Web/API/Boolean /ko/docs/Web/JavaScript/Reference/Global_Objects/Boolean /ko/docs/Web/API/Canvas_API/캔버스_튜토리얼 /ko/docs/Web/API/Canvas_API/Tutorial /ko/docs/Web/API/ChildNode /ko/docs/orphaned/Web/API/ChildNode diff --git a/files/ko/_wikihistory.json b/files/ko/_wikihistory.json index 08e78b3b34..44fb1be3f6 100644 --- a/files/ko/_wikihistory.json +++ b/files/ko/_wikihistory.json @@ -3540,19 +3540,6 @@ "limkukhyun" ] }, - "Web/API/Body": { - "modified": "2020-10-15T22:07:57.321Z", - "contributors": [ - "alattalatta", - "RickBrown" - ] - }, - "Web/API/Body/json": { - "modified": "2020-10-15T22:07:55.949Z", - "contributors": [ - "ldss3sang" - ] - }, "Web/API/BroadcastChannel": { "modified": "2020-10-15T22:17:58.054Z", "contributors": [ @@ -18185,6 +18172,19 @@ "hyeonseok" ] }, + "orphaned/Web/API/Body": { + "modified": "2020-10-15T22:07:57.321Z", + "contributors": [ + "alattalatta", + "RickBrown" + ] + }, + "orphaned/Web/API/Body/json": { + "modified": "2020-10-15T22:07:55.949Z", + "contributors": [ + "ldss3sang" + ] + }, "orphaned/Web/API/ChildNode": { "modified": "2020-10-15T22:04:53.961Z", "contributors": [ diff --git a/files/ko/orphaned/web/api/body/index.html b/files/ko/orphaned/web/api/body/index.html new file mode 100644 index 0000000000..8d315725a1 --- /dev/null +++ b/files/ko/orphaned/web/api/body/index.html @@ -0,0 +1,98 @@ +--- +title: Body +slug: orphaned/Web/API/Body +tags: + - API + - BODY + - Experimental + - Fetch + - Fetch API + - Interface + - Reference + - request +translation_of: Web/API/Body +original_slug: Web/API/Body +--- +
{{ APIRef("Fetch") }}
+ +

The Body {{glossary("mixin")}} of the Fetch API represents the body of the response/request, allowing you to declare what its content type is and how it should be handled.

+ +

Body is implemented by both {{domxref("Request")}} and {{domxref("Response")}}. This provides these objects with an associated body (a stream), a used flag (initially unset), and a MIME type (initially the empty byte sequence).

+ +

Properties

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
A simple getter used to expose a {{domxref("ReadableStream")}} of the body contents.
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
A {{domxref("Boolean")}} that indicates whether the body has been read.
+
+ +

Methods

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{domxref("ArrayBuffer")}}.
+
{{domxref("Body.blob()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("Blob")}}.
+
{{domxref("Body.formData()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("FormData")}} object.
+
{{domxref("Body.json()")}}
+
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")}}.
+
{{domxref("Body.text()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("USVString")}} (text). The response is always decoded using UTF-8.
+
+ +

Examples

+ +

The example below uses a simple fetch call to grab an image and display it in an {{htmlelement("img")}} tag. You'll notice that since we are requesting an image, we need to run {{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} implements body) to give the response its correct MIME type.

+ +

HTML Content

+ +
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
+
+ +

JS Content

+ +
const myImage = document.querySelector('.my-image');
+fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
+	.then(res => res.blob())
+	.then(res => {
+		const objectURL = URL.createObjectURL(res);
+		myImage.src = objectURL;
+});
+ +

{{ EmbedLiveSample('Examples', '100%', '250px') }}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.Body")}}

+ +

See also

+ + + +

 

diff --git a/files/ko/orphaned/web/api/body/json/index.html b/files/ko/orphaned/web/api/body/json/index.html new file mode 100644 index 0000000000..c3c0fa14cc --- /dev/null +++ b/files/ko/orphaned/web/api/body/json/index.html @@ -0,0 +1,74 @@ +--- +title: Body.json() +slug: orphaned/Web/API/Body/json +translation_of: Web/API/Body/json +original_slug: Web/API/Body/json +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Body")}} mixin의 json() 매서드는 {{domxref("Response")}} 스트림을 가져와 스트림이 완료될때까지 읽는다. 이 메서드는 body 텍스트를 {{jsxref("JSON")}}으로 바꾸는 결과로 해결되는 promise를 반환한다.

+ +

구문

+ +
response.json().then(function(data) {
+  // do something with your data
+});
+ +

매개변수

+ +

없음.

+ +

반환값

+ +

A promise that resolves with the result of parsing the body text as JSON. This could be anything that can be represented by JSON — an object, an array, a string, a number...

+ +

Example

+ +

In our fetch json example (run fetch json live), we create a new request using the {{domxref("Request.Request")}} constructor, then use it to fetch a .json file. When the fetch is successful, we read and parse the data using json(), then read values out of the resulting objects as you'd expect and insert them into list items to display our product data.

+ +
var myList = document.querySelector('ul');
+
+var myRequest = new Request('products.json');
+
+fetch(myRequest)
+  .then(function(response) { return response.json(); })
+  .then(function(data) {
+    for (var i = 0; i < data.products.length; i++) {
+      var listItem = document.createElement('li');
+      listItem.innerHTML = '<strong>' + data.products[i].Name + '</strong> can be found in ' +
+                           data.products[i].Location +
+                           '. Cost: <strong>£' + data.products[i].Price + '</strong>';
+      myList.appendChild(listItem);
+    }
+  });
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-json','json()')}}{{Spec2('Fetch')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.Body.json")}}

+ +

See also

+ + diff --git a/files/ko/web/api/body/index.html b/files/ko/web/api/body/index.html deleted file mode 100644 index 6e5cc42061..0000000000 --- a/files/ko/web/api/body/index.html +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: Body -slug: Web/API/Body -tags: - - API - - BODY - - Experimental - - Fetch - - Fetch API - - Interface - - Reference - - request -translation_of: Web/API/Body ---- -
{{ APIRef("Fetch") }}
- -

The Body {{glossary("mixin")}} of the Fetch API represents the body of the response/request, allowing you to declare what its content type is and how it should be handled.

- -

Body is implemented by both {{domxref("Request")}} and {{domxref("Response")}}. This provides these objects with an associated body (a stream), a used flag (initially unset), and a MIME type (initially the empty byte sequence).

- -

Properties

- -
-
{{domxref("Body.body")}} {{readonlyInline}}
-
A simple getter used to expose a {{domxref("ReadableStream")}} of the body contents.
-
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
-
A {{domxref("Boolean")}} that indicates whether the body has been read.
-
- -

Methods

- -
-
{{domxref("Body.arrayBuffer()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{domxref("ArrayBuffer")}}.
-
{{domxref("Body.blob()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("Blob")}}.
-
{{domxref("Body.formData()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("FormData")}} object.
-
{{domxref("Body.json()")}}
-
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")}}.
-
{{domxref("Body.text()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("USVString")}} (text). The response is always decoded using UTF-8.
-
- -

Examples

- -

The example below uses a simple fetch call to grab an image and display it in an {{htmlelement("img")}} tag. You'll notice that since we are requesting an image, we need to run {{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} implements body) to give the response its correct MIME type.

- -

HTML Content

- -
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
-
- -

JS Content

- -
const myImage = document.querySelector('.my-image');
-fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
-	.then(res => res.blob())
-	.then(res => {
-		const objectURL = URL.createObjectURL(res);
-		myImage.src = objectURL;
-});
- -

{{ EmbedLiveSample('Examples', '100%', '250px') }}

- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}} 
- -

Browser compatibility

- - - -

{{Compat("api.Body")}}

- -

See also

- - - -

 

diff --git a/files/ko/web/api/body/json/index.html b/files/ko/web/api/body/json/index.html deleted file mode 100644 index 761720f420..0000000000 --- a/files/ko/web/api/body/json/index.html +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Body.json() -slug: Web/API/Body/json -translation_of: Web/API/Body/json ---- -
{{APIRef("Fetch")}}
- -

{{domxref("Body")}} mixin의 json() 매서드는 {{domxref("Response")}} 스트림을 가져와 스트림이 완료될때까지 읽는다. 이 메서드는 body 텍스트를 {{jsxref("JSON")}}으로 바꾸는 결과로 해결되는 promise를 반환한다.

- -

구문

- -
response.json().then(function(data) {
-  // do something with your data
-});
- -

매개변수

- -

없음.

- -

반환값

- -

A promise that resolves with the result of parsing the body text as JSON. This could be anything that can be represented by JSON — an object, an array, a string, a number...

- -

Example

- -

In our fetch json example (run fetch json live), we create a new request using the {{domxref("Request.Request")}} constructor, then use it to fetch a .json file. When the fetch is successful, we read and parse the data using json(), then read values out of the resulting objects as you'd expect and insert them into list items to display our product data.

- -
var myList = document.querySelector('ul');
-
-var myRequest = new Request('products.json');
-
-fetch(myRequest)
-  .then(function(response) { return response.json(); })
-  .then(function(data) {
-    for (var i = 0; i < data.products.length; i++) {
-      var listItem = document.createElement('li');
-      listItem.innerHTML = '<strong>' + data.products[i].Name + '</strong> can be found in ' +
-                           data.products[i].Location +
-                           '. Cost: <strong>£' + data.products[i].Price + '</strong>';
-      myList.appendChild(listItem);
-    }
-  });
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-json','json()')}}{{Spec2('Fetch')}} 
- -

Browser compatibility

- - - -

{{Compat("api.Body.json")}}

- -

See also

- - diff --git a/files/pt-br/_redirects.txt b/files/pt-br/_redirects.txt index b10eb9b358..e474666e24 100644 --- a/files/pt-br/_redirects.txt +++ b/files/pt-br/_redirects.txt @@ -541,6 +541,8 @@ /pt-BR/docs/Web/API/BatteryManager.ondischargingtimechange /pt-BR/docs/Web/API/BatteryManager/ondischargingtimechange /pt-BR/docs/Web/API/BatteryManager.onlevelchange /pt-BR/docs/Web/API/BatteryManager/onlevelchange /pt-BR/docs/Web/API/BatteryManager/ondischargintimechange /pt-BR/docs/Web/API/BatteryManager/ondischargingtimechange +/pt-BR/docs/Web/API/Body /pt-BR/docs/orphaned/Web/API/Body +/pt-BR/docs/Web/API/Body/json /pt-BR/docs/orphaned/Web/API/Body/json /pt-BR/docs/Web/API/ChildNode /pt-BR/docs/orphaned/Web/API/ChildNode /pt-BR/docs/Web/API/ChildNode/after /pt-BR/docs/orphaned/Web/API/ChildNode/after /pt-BR/docs/Web/API/ChildNode/remove /pt-BR/docs/orphaned/Web/API/ChildNode/remove diff --git a/files/pt-br/_wikihistory.json b/files/pt-br/_wikihistory.json index 113e359f62..1e11ce3d4c 100644 --- a/files/pt-br/_wikihistory.json +++ b/files/pt-br/_wikihistory.json @@ -3813,18 +3813,6 @@ "thiagosaife" ] }, - "Web/API/Body": { - "modified": "2020-10-15T22:30:31.056Z", - "contributors": [ - "Wind1808" - ] - }, - "Web/API/Body/json": { - "modified": "2020-10-15T22:30:29.688Z", - "contributors": [ - "tohdi1" - ] - }, "Web/API/BroadcastChannel": { "modified": "2020-10-15T22:14:45.422Z", "contributors": [ @@ -16987,6 +16975,18 @@ "andre-mendes" ] }, + "orphaned/Web/API/Body": { + "modified": "2020-10-15T22:30:31.056Z", + "contributors": [ + "Wind1808" + ] + }, + "orphaned/Web/API/Body/json": { + "modified": "2020-10-15T22:30:29.688Z", + "contributors": [ + "tohdi1" + ] + }, "orphaned/Web/API/ChildNode": { "modified": "2020-10-15T21:55:14.252Z", "contributors": [ diff --git a/files/pt-br/orphaned/web/api/body/index.html b/files/pt-br/orphaned/web/api/body/index.html new file mode 100644 index 0000000000..fb7edd01c1 --- /dev/null +++ b/files/pt-br/orphaned/web/api/body/index.html @@ -0,0 +1,98 @@ +--- +title: Body +slug: orphaned/Web/API/Body +tags: + - API + - BODY + - Experimental + - Fetch + - Fetch API + - Interface + - NeedsTranslation + - Reference + - TopicStub + - request +translation_of: Web/API/Body +original_slug: Web/API/Body +--- +
{{ APIRef("Fetch") }}
+ +

The Body {{glossary("mixin")}} of the Fetch API represents the body of the response/request, allowing you to declare what its content type is and how it should be handled.

+ +

Body is implemented by both {{domxref("Request")}} and {{domxref("Response")}}. This provides these objects with an associated body (a stream), a used flag (initially unset), and a MIME type (initially the empty byte sequence).

+ +

Properties

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
A simple getter used to expose a {{domxref("ReadableStream")}} of the body contents.
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
A {{jsxref("Boolean")}} that indicates whether the body has been read.
+
+ +

Methods

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{jsxref("ArrayBuffer")}}.
+
{{domxref("Body.blob()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("Blob")}}.
+
{{domxref("Body.formData()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("FormData")}} object.
+
{{domxref("Body.json()")}}
+
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")}}.
+
{{domxref("Body.text()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("USVString")}} (text). The response is always decoded using UTF-8.
+
+ +

Examples

+ +

The example below uses a simple fetch call to grab an image and display it in an {{htmlelement("img")}} tag. You'll notice that since we are requesting an image, we need to run {{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} implements body) to give the response its correct MIME type.

+ +

HTML Content

+ +
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
+
+ +

JS Content

+ +
const myImage = document.querySelector('.my-image');
+fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
+	.then(res => res.blob())
+	.then(res => {
+		const objectURL = URL.createObjectURL(res);
+		myImage.src = objectURL;
+});
+ +

{{ EmbedLiveSample('Examples', '100%', '250px') }}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.Body")}}

+ +

See also

+ + diff --git a/files/pt-br/orphaned/web/api/body/json/index.html b/files/pt-br/orphaned/web/api/body/json/index.html new file mode 100644 index 0000000000..e49273e9ba --- /dev/null +++ b/files/pt-br/orphaned/web/api/body/json/index.html @@ -0,0 +1,90 @@ +--- +title: Body.json() +slug: orphaned/Web/API/Body/json +tags: + - API + - Experimental + - Fetch + - JSON + - Referencia +translation_of: Web/API/Body/json +original_slug: Web/API/Body/json +--- +
{{APIRef("Fetch API")}}
+ +

O método json()  do mixin {{DOMxRef("Body")}} usa uma stream do objeto {{DOMxRef("Response")}} para tratar. O método json() retorna uma Promise como resultado do processamento da stream, retornando um objeto {{JSxRef("JSON")}} em caso de sucesso.

+ +

Syntaxe

+ +
response.json().then(data => {
+  // do something with your data
+});
+ +

Parâmetros

+ +

Nenhum.

+ +

Retorno

+ +

Uma {{jsxref("Promise")}} que retorna um objeto Javascript no método resolve(). Pode ser qualquer tipo que pode ser representado com JSON — objeto, array, string, numeral...

+ +

Exemplo

+ +

Em nosso exemplo de fetch em json (teste aqui a busca em json com fetch), nós criamos uma nova requisição usando o constructor de {{DOMxRef("Request.Request", "Request()")}}, e em seguimos a usamos para buscar um arquivo .json. Quando o fetch é bem-sucedido, nós lemos e tratamos a stream com o método json(), lê os valores em forma de objeto retornados como esperado e inserimos na lista para exibir os dados dos produtos.

+ +
const myList = document.querySelector('ul');
+const myRequest = new Request('products.json');
+
+fetch(myRequest)
+  .then(response => response.json())
+  .then(data => {
+    for (const product of data.products) {
+      let listItem = document.createElement('li');
+      listItem.appendChild(
+        document.createElement('strong')
+      ).textContent = product.Name;
+      listItem.append(
+        ` can be found in ${
+          product.Location
+        }. Cost: `
+      );
+      listItem.appendChild(
+        document.createElement('strong')
+      ).textContent = `£${product.Price}`;
+      myList.appendChild(listItem);
+    }
+  })
+  .catch(console.error);
+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificaçõesStatusComentários
{{SpecName("Fetch", "#dom-body-json", "Body.json()")}}{{Spec2("Fetch")}}Definição Inicial
+ +

Compatibilidade de Navegador

+ + + +

{{Compat("api.Body.json")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/body/index.html b/files/pt-br/web/api/body/index.html deleted file mode 100644 index 121e93718b..0000000000 --- a/files/pt-br/web/api/body/index.html +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: Body -slug: Web/API/Body -tags: - - API - - BODY - - Experimental - - Fetch - - Fetch API - - Interface - - NeedsTranslation - - Reference - - TopicStub - - request -translation_of: Web/API/Body ---- -
{{ APIRef("Fetch") }}
- -

The Body {{glossary("mixin")}} of the Fetch API represents the body of the response/request, allowing you to declare what its content type is and how it should be handled.

- -

Body is implemented by both {{domxref("Request")}} and {{domxref("Response")}}. This provides these objects with an associated body (a stream), a used flag (initially unset), and a MIME type (initially the empty byte sequence).

- -

Properties

- -
-
{{domxref("Body.body")}} {{readonlyInline}}
-
A simple getter used to expose a {{domxref("ReadableStream")}} of the body contents.
-
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
-
A {{jsxref("Boolean")}} that indicates whether the body has been read.
-
- -

Methods

- -
-
{{domxref("Body.arrayBuffer()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{jsxref("ArrayBuffer")}}.
-
{{domxref("Body.blob()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("Blob")}}.
-
{{domxref("Body.formData()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("FormData")}} object.
-
{{domxref("Body.json()")}}
-
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")}}.
-
{{domxref("Body.text()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("USVString")}} (text). The response is always decoded using UTF-8.
-
- -

Examples

- -

The example below uses a simple fetch call to grab an image and display it in an {{htmlelement("img")}} tag. You'll notice that since we are requesting an image, we need to run {{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} implements body) to give the response its correct MIME type.

- -

HTML Content

- -
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
-
- -

JS Content

- -
const myImage = document.querySelector('.my-image');
-fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
-	.then(res => res.blob())
-	.then(res => {
-		const objectURL = URL.createObjectURL(res);
-		myImage.src = objectURL;
-});
- -

{{ EmbedLiveSample('Examples', '100%', '250px') }}

- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}}
- -

Browser compatibility

- - - -

{{Compat("api.Body")}}

- -

See also

- - diff --git a/files/pt-br/web/api/body/json/index.html b/files/pt-br/web/api/body/json/index.html deleted file mode 100644 index 7ee4482fe5..0000000000 --- a/files/pt-br/web/api/body/json/index.html +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: Body.json() -slug: Web/API/Body/json -tags: - - API - - Experimental - - Fetch - - JSON - - Referencia -translation_of: Web/API/Body/json ---- -
{{APIRef("Fetch API")}}
- -

O método json()  do mixin {{DOMxRef("Body")}} usa uma stream do objeto {{DOMxRef("Response")}} para tratar. O método json() retorna uma Promise como resultado do processamento da stream, retornando um objeto {{JSxRef("JSON")}} em caso de sucesso.

- -

Syntaxe

- -
response.json().then(data => {
-  // do something with your data
-});
- -

Parâmetros

- -

Nenhum.

- -

Retorno

- -

Uma {{jsxref("Promise")}} que retorna um objeto Javascript no método resolve(). Pode ser qualquer tipo que pode ser representado com JSON — objeto, array, string, numeral...

- -

Exemplo

- -

Em nosso exemplo de fetch em json (teste aqui a busca em json com fetch), nós criamos uma nova requisição usando o constructor de {{DOMxRef("Request.Request", "Request()")}}, e em seguimos a usamos para buscar um arquivo .json. Quando o fetch é bem-sucedido, nós lemos e tratamos a stream com o método json(), lê os valores em forma de objeto retornados como esperado e inserimos na lista para exibir os dados dos produtos.

- -
const myList = document.querySelector('ul');
-const myRequest = new Request('products.json');
-
-fetch(myRequest)
-  .then(response => response.json())
-  .then(data => {
-    for (const product of data.products) {
-      let listItem = document.createElement('li');
-      listItem.appendChild(
-        document.createElement('strong')
-      ).textContent = product.Name;
-      listItem.append(
-        ` can be found in ${
-          product.Location
-        }. Cost: `
-      );
-      listItem.appendChild(
-        document.createElement('strong')
-      ).textContent = `£${product.Price}`;
-      myList.appendChild(listItem);
-    }
-  })
-  .catch(console.error);
- -

Especificações

- - - - - - - - - - - - - - - - -
SpecificaçõesStatusComentários
{{SpecName("Fetch", "#dom-body-json", "Body.json()")}}{{Spec2("Fetch")}}Definição Inicial
- -

Compatibilidade de Navegador

- - - -

{{Compat("api.Body.json")}}

- -

Veja também

- - diff --git a/files/ru/_redirects.txt b/files/ru/_redirects.txt index aacd2743c2..f5f6f28e1c 100644 --- a/files/ru/_redirects.txt +++ b/files/ru/_redirects.txt @@ -373,6 +373,10 @@ /ru/docs/Web/API/AudioContext/createPanner /ru/docs/Web/API/BaseAudioContext/createPanner /ru/docs/Web/API/AudioContext/currentTime /ru/docs/Web/API/BaseAudioContext/currentTime /ru/docs/Web/API/AudioContext/decodeAudioData /ru/docs/Web/API/BaseAudioContext/decodeAudioData +/ru/docs/Web/API/Body /ru/docs/orphaned/Web/API/Body +/ru/docs/Web/API/Body/arrayBuffer /ru/docs/orphaned/Web/API/Body/arrayBuffer +/ru/docs/Web/API/Body/formData /ru/docs/orphaned/Web/API/Body/formData +/ru/docs/Web/API/Body/json /ru/docs/orphaned/Web/API/Body/json /ru/docs/Web/API/CSS_Object_Model/ориентация_экрана /ru/docs/Web/API/CSS_Object_Model/Managing_screen_orientation /ru/docs/Web/API/Canvas_API/Tutorial/Использование_изображений /ru/docs/Web/API/Canvas_API/Tutorial/Using_images /ru/docs/Web/API/Canvas_API/Tutorial/Композиции /ru/docs/Web/API/Canvas_API/Tutorial/Compositing diff --git a/files/ru/_wikihistory.json b/files/ru/_wikihistory.json index 99f463b01f..e2d0334fd9 100644 --- a/files/ru/_wikihistory.json +++ b/files/ru/_wikihistory.json @@ -5799,30 +5799,6 @@ "sh7dm" ] }, - "Web/API/Body": { - "modified": "2020-10-15T22:06:24.327Z", - "contributors": [ - "RickBrown" - ] - }, - "Web/API/Body/arrayBuffer": { - "modified": "2020-10-15T22:12:53.458Z", - "contributors": [ - "SerzN1" - ] - }, - "Web/API/Body/formData": { - "modified": "2020-10-15T22:14:02.669Z", - "contributors": [ - "Aparin" - ] - }, - "Web/API/Body/json": { - "modified": "2020-10-15T22:06:25.317Z", - "contributors": [ - "dasha_hshr" - ] - }, "Web/API/BroadcastChannel": { "modified": "2020-10-15T22:08:52.446Z", "contributors": [ @@ -25274,6 +25250,30 @@ "a-chepugov" ] }, + "orphaned/Web/API/Body": { + "modified": "2020-10-15T22:06:24.327Z", + "contributors": [ + "RickBrown" + ] + }, + "orphaned/Web/API/Body/arrayBuffer": { + "modified": "2020-10-15T22:12:53.458Z", + "contributors": [ + "SerzN1" + ] + }, + "orphaned/Web/API/Body/formData": { + "modified": "2020-10-15T22:14:02.669Z", + "contributors": [ + "Aparin" + ] + }, + "orphaned/Web/API/Body/json": { + "modified": "2020-10-15T22:06:25.317Z", + "contributors": [ + "dasha_hshr" + ] + }, "orphaned/Web/API/ChildNode": { "modified": "2019-03-23T22:51:21.900Z", "contributors": [ diff --git a/files/ru/orphaned/web/api/body/arraybuffer/index.html b/files/ru/orphaned/web/api/body/arraybuffer/index.html new file mode 100644 index 0000000000..8c2e092cf3 --- /dev/null +++ b/files/ru/orphaned/web/api/body/arraybuffer/index.html @@ -0,0 +1,91 @@ +--- +title: Body.arrayBuffer() +slug: orphaned/Web/API/Body/arrayBuffer +tags: + - API + - Экспериментальный + - справочник +translation_of: Web/API/Body/arrayBuffer +original_slug: Web/API/Body/arrayBuffer +--- +
{{APIRef("Fetch")}}
+ +

Метод arrayBuffer() из примеси(mixin) {{domxref("Body")}} берёт поток(stream) {{domxref("Response")}} и читает его до завершения. Он возвращает промис, который будет успешно завершён с помощью {{domxref("ArrayBuffer")}}.

+ +

Синтаксис

+ +
response.arrayBuffer().then(function(buffer) {
+  // можно сделать что либо с буфером
+});
+ +

Параметры

+ +

Нат параметров.

+ +

Возвращаемое значение

+ +

Промис, который содержит {{domxref("ArrayBuffer")}}.

+ +

Пример

+ +

В нашем примере живой загрузки с array buffer есть кнопка Play. При нажатии на кнопку вызывается функция getData(). Стоит учесть что до проигрывания аудио файл будет скачан целиком. Если вам необходимо начать воспроизведение файла ogg во время загрузки (стримить аудио) - то лучше рассмотреть  {{domxref("HTMLAudioElement")}}:

+ +
new Audio(music.ogg).play()
+
+ +

В функции getData() мы создаём новый запрос используя конструктор {{domxref("Request.Request")}}, после этого используем его чтобы загрузить OGG звук. Мы также используем {{domxref("AudioContext.createBufferSource")}} чтобы создать ресурс аудиобуффера. При успешном завершении запроса, мы считываем {{domxref("ArrayBuffer")}} из ответа используя arrayBuffer(), декодируем аудио с помощью {{domxref("AudioContext.decodeAudioData")}}, устанавливаем раскодированные данные как ресурс аудио буфера (source.buffer), затем используем данные этого ресурса в  {{domxref("AudioContext.destination")}}.

+ +

Когда функция getData() заканчивает своё выполнение, мы стартуем проигрывание аудио ресурса функцией start(0), потом блокируем кнопку проигрывания для предотвращения повторного проигрывания (это может привести к ошибкам)

+ +
function getData() {
+  source = audioCtx.createBufferSource();
+
+  var myRequest = new Request('viper.ogg');
+
+  fetch(myRequest).then(function(response) {
+    return response.arrayBuffer();
+  }).then(function(buffer) {
+    audioCtx.decodeAudioData(buffer, function(decodedData) {
+      source.buffer = decodedData;
+      source.connect(audioCtx.destination);
+    });
+  });
+};
+
+// навешиваем обработчики старт и стоп на кнопку
+play.onclick = function() {
+  getData();
+  source.start(0);
+  play.setAttribute('disabled', 'disabled');
+}
+ +

Спецификация

+ + + + + + + + + + + + + + +
СпецификацияСтатусКомментарии
{{SpecName('Fetch','#dom-body-arraybuffer','arrayBuffer()')}}{{Spec2('Fetch')}} 
+ +

Поддержка браузерами

+ + + +

{{Compat("api.Body.arrayBuffer")}}

+ +

Смотрите также

+ + diff --git a/files/ru/orphaned/web/api/body/formdata/index.html b/files/ru/orphaned/web/api/body/formdata/index.html new file mode 100644 index 0000000000..5e04b96274 --- /dev/null +++ b/files/ru/orphaned/web/api/body/formdata/index.html @@ -0,0 +1,60 @@ +--- +title: Body.formData() +slug: orphaned/Web/API/Body/formData +translation_of: Web/API/Body/formData +original_slug: Web/API/Body/formData +--- +
{{APIRef("Fetch")}}
+ +

Метод formData() из {{domxref("Body")}} принимает поток ответа {{domxref("Response")}} и считывает его до завершения. Он возвращает промис, который разрешается с помощью объекта {{domxref("FormData")}}.

+ +
+

Примечание:  Это в основном относится к service workers. Если пользователь отправляет форму а service worker перехватывает запрос,  можно, например, вызвать formData() чтобы получить набор данных в формате ключ-значение, изменить некоторые поля, а затем отправить форму на сервер, или использовать её локально.

+
+ +

Синтаксис

+ +
response.formData()
+.then(function(formdata) {
+  // do something with your formdata
+});
+ +

Параметры

+ +

Нет.

+ +

Возвращаемое значение

+ +

{{domxref("Promise")}} которое разрешается с помощью объекта {{domxref("FormData")}}.

+ +

Пример

+ +

Нужно добавить.

+ +

Спецификации

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-formdata','formData()')}}{{Spec2('Fetch')}} 
+ +

Браузерная совместимость

+

{{Compat("api.Body.formData")}}

+ +

Также смотрите

+ + diff --git a/files/ru/orphaned/web/api/body/index.html b/files/ru/orphaned/web/api/body/index.html new file mode 100644 index 0000000000..0794ac997e --- /dev/null +++ b/files/ru/orphaned/web/api/body/index.html @@ -0,0 +1,100 @@ +--- +title: Body +slug: orphaned/Web/API/Body +tags: + - API + - BODY + - Experimental + - Fetch + - Fetch API + - Interface + - NeedsTranslation + - Reference + - TopicStub + - request +translation_of: Web/API/Body +original_slug: Web/API/Body +--- +
{{ APIRef("Fetch") }}
+ +

The Body {{glossary("mixin")}} of the Fetch API represents the body of the response/request, allowing you to declare what its content type is and how it should be handled.

+ +

Body is implemented by both {{domxref("Request")}} and {{domxref("Response")}}. This provides these objects with an associated body (a stream), a used flag (initially unset), and a MIME type (initially the empty byte sequence).

+ +

Properties

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
A simple getter used to expose a {{domxref("ReadableStream")}} of the body contents.
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
A {{domxref("Boolean")}} that indicates whether the body has been read.
+
+ +

Methods

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{domxref("ArrayBuffer")}}.
+
{{domxref("Body.blob()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("Blob")}}.
+
{{domxref("Body.formData()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("FormData")}} object.
+
{{domxref("Body.json()")}}
+
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")}}.
+
{{domxref("Body.text()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("USVString")}} (text). The response is always decoded using UTF-8.
+
+ +

Examples

+ +

The example below uses a simple fetch call to grab an image and display it in an {{htmlelement("img")}} tag. You'll notice that since we are requesting an image, we need to run {{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} implements body) to give the response its correct MIME type.

+ +

HTML Content

+ +
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
+
+ +

JS Content

+ +
var myImage = document.querySelector('.my-image');
+fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
+	.then(res => res.blob())
+	.then(res => {
+		var objectURL = URL.createObjectURL(res);
+		myImage.src = objectURL;
+});
+ +

{{ EmbedLiveSample('Examples', '100%', '250px') }}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.Body")}}

+ +

See also

+ + + +

 

diff --git a/files/ru/orphaned/web/api/body/json/index.html b/files/ru/orphaned/web/api/body/json/index.html new file mode 100644 index 0000000000..ae8657f9bb --- /dev/null +++ b/files/ru/orphaned/web/api/body/json/index.html @@ -0,0 +1,75 @@ +--- +title: Body.json() +slug: orphaned/Web/API/Body/json +tags: + - Fetch-запрос + - Справка + - метод +translation_of: Web/API/Body/json +original_slug: Web/API/Body/json +--- +
{{APIRef("Fetch")}}
+ +

Метод json() , определён на миксине {{domxref("Body")}}, который включён в объектах Request и Response, принимает и читает тело {{domxref("Response")}} stream. Возвращает промис, который, когда ответ будет получен, вызовет колбэк с результатом парсинга тела ответа в {{jsxref("JSON")}} объект.

+ +

Синтаксис

+ +
response.json().then(function(data) {
+  // do something with your data
+});
+ +

Аргументы

+ +

Нет.

+ +

Возвращает

+ +

Промис, который, когда ответ будет получен, вызовет колбэк с результатом парсинга тела ответа в JSON объект. Этим может быть что угодно, что может быть представлено как JSON объект — объект, массив, строка, число...

+ +

Пример

+ +

В нашем fetch json примере (запустите fetch json live), мы создаём новый запрос, используя {{domxref("Request.Request")}} конструктор, в последствии мы используем его (запрос) для получения .json файла. Когда fetch запрос будет выполнен, мы прочтём и спарсим данные, используя json(), а далее вставим значения из полученного объекта в list элементы списка для отображения данных по нашему продукту.

+ +
var myList = document.querySelector('ul');
+
+var myRequest = new Request('products.json');
+
+fetch(myRequest)
+  .then(function(response) { return response.json(); })
+  .then(function(data) {
+    for (var i = 0; i < data.products.length; i++) {
+      var listItem = document.createElement('li');
+      listItem.innerHTML = '<strong>' + data.products[i].Name + '</strong> can be found in ' +
+                           data.products[i].Location +
+                           '. Cost: <strong>£' + data.products[i].Price + '</strong>';
+      myList.appendChild(listItem);
+    }
+  });
+ +

Спецификации

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-json','json()')}}{{Spec2('Fetch')}} 
+ +

Совместимость с браузерами

+

{{Compat("api.Body.json")}}

+ +

Смотрите также

+ + diff --git a/files/ru/web/api/body/arraybuffer/index.html b/files/ru/web/api/body/arraybuffer/index.html deleted file mode 100644 index a9dbd21162..0000000000 --- a/files/ru/web/api/body/arraybuffer/index.html +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: Body.arrayBuffer() -slug: Web/API/Body/arrayBuffer -tags: - - API - - Экспериментальный - - справочник -translation_of: Web/API/Body/arrayBuffer ---- -
{{APIRef("Fetch")}}
- -

Метод arrayBuffer() из примеси(mixin) {{domxref("Body")}} берёт поток(stream) {{domxref("Response")}} и читает его до завершения. Он возвращает промис, который будет успешно завершён с помощью {{domxref("ArrayBuffer")}}.

- -

Синтаксис

- -
response.arrayBuffer().then(function(buffer) {
-  // можно сделать что либо с буфером
-});
- -

Параметры

- -

Нат параметров.

- -

Возвращаемое значение

- -

Промис, который содержит {{domxref("ArrayBuffer")}}.

- -

Пример

- -

В нашем примере живой загрузки с array buffer есть кнопка Play. При нажатии на кнопку вызывается функция getData(). Стоит учесть что до проигрывания аудио файл будет скачан целиком. Если вам необходимо начать воспроизведение файла ogg во время загрузки (стримить аудио) - то лучше рассмотреть  {{domxref("HTMLAudioElement")}}:

- -
new Audio(music.ogg).play()
-
- -

В функции getData() мы создаём новый запрос используя конструктор {{domxref("Request.Request")}}, после этого используем его чтобы загрузить OGG звук. Мы также используем {{domxref("AudioContext.createBufferSource")}} чтобы создать ресурс аудиобуффера. При успешном завершении запроса, мы считываем {{domxref("ArrayBuffer")}} из ответа используя arrayBuffer(), декодируем аудио с помощью {{domxref("AudioContext.decodeAudioData")}}, устанавливаем раскодированные данные как ресурс аудио буфера (source.buffer), затем используем данные этого ресурса в  {{domxref("AudioContext.destination")}}.

- -

Когда функция getData() заканчивает своё выполнение, мы стартуем проигрывание аудио ресурса функцией start(0), потом блокируем кнопку проигрывания для предотвращения повторного проигрывания (это может привести к ошибкам)

- -
function getData() {
-  source = audioCtx.createBufferSource();
-
-  var myRequest = new Request('viper.ogg');
-
-  fetch(myRequest).then(function(response) {
-    return response.arrayBuffer();
-  }).then(function(buffer) {
-    audioCtx.decodeAudioData(buffer, function(decodedData) {
-      source.buffer = decodedData;
-      source.connect(audioCtx.destination);
-    });
-  });
-};
-
-// навешиваем обработчики старт и стоп на кнопку
-play.onclick = function() {
-  getData();
-  source.start(0);
-  play.setAttribute('disabled', 'disabled');
-}
- -

Спецификация

- - - - - - - - - - - - - - -
СпецификацияСтатусКомментарии
{{SpecName('Fetch','#dom-body-arraybuffer','arrayBuffer()')}}{{Spec2('Fetch')}} 
- -

Поддержка браузерами

- - - -

{{Compat("api.Body.arrayBuffer")}}

- -

Смотрите также

- - diff --git a/files/ru/web/api/body/formdata/index.html b/files/ru/web/api/body/formdata/index.html deleted file mode 100644 index 23b5b001f1..0000000000 --- a/files/ru/web/api/body/formdata/index.html +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: Body.formData() -slug: Web/API/Body/formData -translation_of: Web/API/Body/formData ---- -
{{APIRef("Fetch")}}
- -

Метод formData() из {{domxref("Body")}} принимает поток ответа {{domxref("Response")}} и считывает его до завершения. Он возвращает промис, который разрешается с помощью объекта {{domxref("FormData")}}.

- -
-

Примечание:  Это в основном относится к service workers. Если пользователь отправляет форму а service worker перехватывает запрос,  можно, например, вызвать formData() чтобы получить набор данных в формате ключ-значение, изменить некоторые поля, а затем отправить форму на сервер, или использовать её локально.

-
- -

Синтаксис

- -
response.formData()
-.then(function(formdata) {
-  // do something with your formdata
-});
- -

Параметры

- -

Нет.

- -

Возвращаемое значение

- -

{{domxref("Promise")}} которое разрешается с помощью объекта {{domxref("FormData")}}.

- -

Пример

- -

Нужно добавить.

- -

Спецификации

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-formdata','formData()')}}{{Spec2('Fetch')}} 
- -

Браузерная совместимость

-

{{Compat("api.Body.formData")}}

- -

Также смотрите

- - diff --git a/files/ru/web/api/body/index.html b/files/ru/web/api/body/index.html deleted file mode 100644 index 82ba54e53d..0000000000 --- a/files/ru/web/api/body/index.html +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Body -slug: Web/API/Body -tags: - - API - - BODY - - Experimental - - Fetch - - Fetch API - - Interface - - NeedsTranslation - - Reference - - TopicStub - - request -translation_of: Web/API/Body ---- -
{{ APIRef("Fetch") }}
- -

The Body {{glossary("mixin")}} of the Fetch API represents the body of the response/request, allowing you to declare what its content type is and how it should be handled.

- -

Body is implemented by both {{domxref("Request")}} and {{domxref("Response")}}. This provides these objects with an associated body (a stream), a used flag (initially unset), and a MIME type (initially the empty byte sequence).

- -

Properties

- -
-
{{domxref("Body.body")}} {{readonlyInline}}
-
A simple getter used to expose a {{domxref("ReadableStream")}} of the body contents.
-
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
-
A {{domxref("Boolean")}} that indicates whether the body has been read.
-
- -

Methods

- -
-
{{domxref("Body.arrayBuffer()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{domxref("ArrayBuffer")}}.
-
{{domxref("Body.blob()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("Blob")}}.
-
{{domxref("Body.formData()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("FormData")}} object.
-
{{domxref("Body.json()")}}
-
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")}}.
-
{{domxref("Body.text()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("USVString")}} (text). The response is always decoded using UTF-8.
-
- -

Examples

- -

The example below uses a simple fetch call to grab an image and display it in an {{htmlelement("img")}} tag. You'll notice that since we are requesting an image, we need to run {{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} implements body) to give the response its correct MIME type.

- -

HTML Content

- -
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
-
- -

JS Content

- -
var myImage = document.querySelector('.my-image');
-fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
-	.then(res => res.blob())
-	.then(res => {
-		var objectURL = URL.createObjectURL(res);
-		myImage.src = objectURL;
-});
- -

{{ EmbedLiveSample('Examples', '100%', '250px') }}

- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}} 
- -

Browser compatibility

- - - -

{{Compat("api.Body")}}

- -

See also

- - - -

 

diff --git a/files/ru/web/api/body/json/index.html b/files/ru/web/api/body/json/index.html deleted file mode 100644 index df9cdeb49b..0000000000 --- a/files/ru/web/api/body/json/index.html +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: Body.json() -slug: Web/API/Body/json -tags: - - Fetch-запрос - - Справка - - метод -translation_of: Web/API/Body/json ---- -
{{APIRef("Fetch")}}
- -

Метод json() , определён на миксине {{domxref("Body")}}, который включён в объектах Request и Response, принимает и читает тело {{domxref("Response")}} stream. Возвращает промис, который, когда ответ будет получен, вызовет колбэк с результатом парсинга тела ответа в {{jsxref("JSON")}} объект.

- -

Синтаксис

- -
response.json().then(function(data) {
-  // do something with your data
-});
- -

Аргументы

- -

Нет.

- -

Возвращает

- -

Промис, который, когда ответ будет получен, вызовет колбэк с результатом парсинга тела ответа в JSON объект. Этим может быть что угодно, что может быть представлено как JSON объект — объект, массив, строка, число...

- -

Пример

- -

В нашем fetch json примере (запустите fetch json live), мы создаём новый запрос, используя {{domxref("Request.Request")}} конструктор, в последствии мы используем его (запрос) для получения .json файла. Когда fetch запрос будет выполнен, мы прочтём и спарсим данные, используя json(), а далее вставим значения из полученного объекта в list элементы списка для отображения данных по нашему продукту.

- -
var myList = document.querySelector('ul');
-
-var myRequest = new Request('products.json');
-
-fetch(myRequest)
-  .then(function(response) { return response.json(); })
-  .then(function(data) {
-    for (var i = 0; i < data.products.length; i++) {
-      var listItem = document.createElement('li');
-      listItem.innerHTML = '<strong>' + data.products[i].Name + '</strong> can be found in ' +
-                           data.products[i].Location +
-                           '. Cost: <strong>£' + data.products[i].Price + '</strong>';
-      myList.appendChild(listItem);
-    }
-  });
- -

Спецификации

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-json','json()')}}{{Spec2('Fetch')}} 
- -

Совместимость с браузерами

-

{{Compat("api.Body.json")}}

- -

Смотрите также

- - diff --git a/files/zh-cn/_redirects.txt b/files/zh-cn/_redirects.txt index 46df9ce2f8..700295744c 100644 --- a/files/zh-cn/_redirects.txt +++ b/files/zh-cn/_redirects.txt @@ -1458,6 +1458,14 @@ /zh-CN/docs/Web/API/Blob.size /zh-CN/docs/Web/API/Blob/size /zh-CN/docs/Web/API/Blob.slice /zh-CN/docs/Web/API/Blob/slice /zh-CN/docs/Web/API/Blob.type /zh-CN/docs/Web/API/Blob/type +/zh-CN/docs/Web/API/Body /zh-CN/docs/orphaned/Web/API/Body +/zh-CN/docs/Web/API/Body/arrayBuffer /zh-CN/docs/orphaned/Web/API/Body/arrayBuffer +/zh-CN/docs/Web/API/Body/blob /zh-CN/docs/orphaned/Web/API/Body/blob +/zh-CN/docs/Web/API/Body/body /zh-CN/docs/orphaned/Web/API/Body/body +/zh-CN/docs/Web/API/Body/bodyUsed /zh-CN/docs/orphaned/Web/API/Body/bodyUsed +/zh-CN/docs/Web/API/Body/formData /zh-CN/docs/orphaned/Web/API/Body/formData +/zh-CN/docs/Web/API/Body/json /zh-CN/docs/orphaned/Web/API/Body/json +/zh-CN/docs/Web/API/Body/text /zh-CN/docs/orphaned/Web/API/Body/text /zh-CN/docs/Web/API/CSSMatrix /zh-CN/docs/conflicting/Web/API/DOMMatrix /zh-CN/docs/Web/API/CSSStyleSheet.insertRule /zh-CN/docs/Web/API/CSSStyleSheet/insertRule /zh-CN/docs/Web/API/CSS分页规则 /zh-CN/docs/Web/API/CSSPageRule diff --git a/files/zh-cn/_wikihistory.json b/files/zh-cn/_wikihistory.json index 3757fd8d23..32a7ea623b 100644 --- a/files/zh-cn/_wikihistory.json +++ b/files/zh-cn/_wikihistory.json @@ -8283,71 +8283,6 @@ "hefang" ] }, - "Web/API/Body": { - "modified": "2020-10-15T21:39:41.630Z", - "contributors": [ - "jason-grimm", - "xgqfrms-GitHub", - "chaosdog", - "Soyaine", - "Jeff-Kook", - "git-lt", - "fscholz" - ] - }, - "Web/API/Body/arrayBuffer": { - "modified": "2019-03-23T22:45:19.643Z", - "contributors": [ - "budblack", - "eqielb" - ] - }, - "Web/API/Body/blob": { - "modified": "2019-03-23T22:13:57.339Z", - "contributors": [ - "fyzhu", - "xiaoyixiang", - "xgqfrms-GitHub", - "thomastao0215" - ] - }, - "Web/API/Body/body": { - "modified": "2020-10-15T22:02:01.208Z", - "contributors": [ - "jason-grimm", - "jcsahnwaldt", - "Axue" - ] - }, - "Web/API/Body/bodyUsed": { - "modified": "2019-03-23T22:13:03.228Z", - "contributors": [ - "chaosdog" - ] - }, - "Web/API/Body/formData": { - "modified": "2019-03-23T22:03:43.519Z", - "contributors": [ - "Gscienty" - ] - }, - "Web/API/Body/json": { - "modified": "2020-10-15T21:54:35.260Z", - "contributors": [ - "RainSlide", - "Soyaine", - "PeixuanLi", - "linmodev", - "xgqfrms-GitHub" - ] - }, - "Web/API/Body/text": { - "modified": "2020-10-15T22:01:11.954Z", - "contributors": [ - "RainSlide", - "zhihongzhong" - ] - }, "Web/API/BroadcastChannel": { "modified": "2020-10-15T22:17:57.354Z", "contributors": [ @@ -49774,6 +49709,71 @@ "smilewalker" ] }, + "orphaned/Web/API/Body": { + "modified": "2020-10-15T21:39:41.630Z", + "contributors": [ + "jason-grimm", + "xgqfrms-GitHub", + "chaosdog", + "Soyaine", + "Jeff-Kook", + "git-lt", + "fscholz" + ] + }, + "orphaned/Web/API/Body/arrayBuffer": { + "modified": "2019-03-23T22:45:19.643Z", + "contributors": [ + "budblack", + "eqielb" + ] + }, + "orphaned/Web/API/Body/blob": { + "modified": "2019-03-23T22:13:57.339Z", + "contributors": [ + "fyzhu", + "xiaoyixiang", + "xgqfrms-GitHub", + "thomastao0215" + ] + }, + "orphaned/Web/API/Body/body": { + "modified": "2020-10-15T22:02:01.208Z", + "contributors": [ + "jason-grimm", + "jcsahnwaldt", + "Axue" + ] + }, + "orphaned/Web/API/Body/bodyUsed": { + "modified": "2019-03-23T22:13:03.228Z", + "contributors": [ + "chaosdog" + ] + }, + "orphaned/Web/API/Body/formData": { + "modified": "2019-03-23T22:03:43.519Z", + "contributors": [ + "Gscienty" + ] + }, + "orphaned/Web/API/Body/json": { + "modified": "2020-10-15T21:54:35.260Z", + "contributors": [ + "RainSlide", + "Soyaine", + "PeixuanLi", + "linmodev", + "xgqfrms-GitHub" + ] + }, + "orphaned/Web/API/Body/text": { + "modified": "2020-10-15T22:01:11.954Z", + "contributors": [ + "RainSlide", + "zhihongzhong" + ] + }, "orphaned/Web/API/ChildNode": { "modified": "2020-10-15T21:30:05.058Z", "contributors": [ diff --git a/files/zh-cn/orphaned/web/api/body/arraybuffer/index.html b/files/zh-cn/orphaned/web/api/body/arraybuffer/index.html new file mode 100644 index 0000000000..5d7acf678f --- /dev/null +++ b/files/zh-cn/orphaned/web/api/body/arraybuffer/index.html @@ -0,0 +1,143 @@ +--- +title: Body.arrayBuffer() +slug: orphaned/Web/API/Body/arrayBuffer +translation_of: Web/API/Body/arrayBuffer +original_slug: Web/API/Body/arrayBuffer +--- +

{{APIRef("Fetch")}}{{ SeeCompatTable() }}

+ +

 {{domxref("Body")}}上的方法 arrayBuffer() 接受一个 {{domxref("Response")}} 流, 并等待其读取完成. 它返回一个 promise 实例, 并 resolve 一个 {{domxref("ArrayBuffer")}} 对象.

+ +

语法

+ +
response.arrayBuffer().then(function(buffer) {
+  // do something with buffer
+)};
+ +

参数

+ +

无。

+ +

返回值

+ +

A promise that resolves with an {{domxref("ArrayBuffer")}}.

+ +

例子

+ +

In our fetch array buffer example (run fetch array buffer live), we have a Play button. When pressed, the getData() function is run.

+ +

In getData() we create a new request using the {{domxref("Request.Request")}} constructor, then use it to fetch an OGG music track. We also use {{domxref("AudioContext.createBufferSource")}} to create an audio buffer source.  When the fetch is successful, we read an {{domxref("ArrayBuffer")}} out of the response using arrayBuffer(), decode the audio data using {{domxref("AudioContext.decodeAudioData")}}, set the decoded data as the audio buffer source's buffer (source.buffer), then connect the source up to the {{domxref("AudioContext.destination")}}.

+ +

Once getData() has finished running, we start the audio source playing with start(0), then disable the play button so it can't be clicked again when it is already playing (this would cause an error.)

+ +
function getData() {
+  source = audioCtx.createBufferSource();
+
+  var myRequest = new Request('viper.ogg');
+
+  fetch(myRequest).then(function(response) {
+    response.arrayBuffer().then(function(buffer) {
+      audioCtx.decodeAudioData(buffer, function(decodedData) {
+        source.buffer = decodedData;
+        source.connect(audioCtx.destination);
+      });
+    });
+  });
+};
+
+// wire up buttons to stop and play audio
+
+play.onclick = function() {
+  getData();
+  source.start(0);
+  play.setAttribute('disabled', 'disabled');
+}
+ +

标准

+ + + + + + + + + + + + + + +
标准状态备注
{{SpecName('Fetch','#dom-body-arraybuffer','arrayBuffer()')}}{{Spec2('Fetch')}} 
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatChrome(41) }}[1]
+ {{ CompatChrome(42) }}
+  
34[1]
+ {{ CompatGeckoDesktop(39)}}
{{ CompatNo }} +

28[1]
+ 29

+
{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

[1] In Chrome 42, Firefox 34 and Opera 28 support for arrayBuffer() was hidden behind a preference.

+ +

参考

+ + + + diff --git a/files/zh-cn/orphaned/web/api/body/blob/index.html b/files/zh-cn/orphaned/web/api/body/blob/index.html new file mode 100644 index 0000000000..4f09632307 --- /dev/null +++ b/files/zh-cn/orphaned/web/api/body/blob/index.html @@ -0,0 +1,137 @@ +--- +title: Body.blob() +slug: orphaned/Web/API/Body/blob +tags: + - Body.blob() +translation_of: Web/API/Body/blob +original_slug: Web/API/Body/blob +--- +

{{APIRef("Fetch")}}

+ +

{{domxref("Body")}}  mixin的 blob()方法使用一个 {{domxref("Response")}} 流,并将其读取完成。它返回一个使用{{domxref("Blob")}}解决的promise。

+ +

句法

+ +
response.blob().then(function(myBlob) {
+  // do something with myBlob
+});
+ +

参数

+ +

None.

+ +

返回值

+ +

A promise that resolves with a {{domxref("Blob")}}.

+ +

例子

+ +

在我们 fetch request example (run fetch request live)中,我们使用Request.Request构造方法创建了一个新的request对象,然后使用它来获取一个JPG文件。当fetch成功的时候,我们使用blob()从response中读取一个Blob对象,并使用URL.createObjectURL 将它放入一个object URL ,然后把URL设置为img元素的src属性以显示这张图片。

+ +

 

+ +
var myImage = document.querySelector('img');
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest)
+.then(function(response) {
+  return response.blob();
+})
+.then(function(myBlob) {
+  var objectURL = URL.createObjectURL(myBlob);
+  myImage.src = objectURL;
+});
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态说明
{{SpecName('Fetch','#dom-body-blob','blob()')}}{{Spec2('Fetch')}} 
+ +

浏览器兼容性

+ +

{{ CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatChrome(42) }} [1]
+  
{{CompatVersionUnknown}}{{ CompatGeckoDesktop(39)}} [2]{{ CompatNo }} +

29 [3]

+
{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo }}{{CompatVersionUnknown}}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

[1] Behind a preference in version 41.

+ +

[2] Behind a preference starting with version 34.

+ +

[3] Behind a preference in version 28.

+ +

另见

+ + diff --git a/files/zh-cn/orphaned/web/api/body/body/index.html b/files/zh-cn/orphaned/web/api/body/body/index.html new file mode 100644 index 0000000000..abf63535fc --- /dev/null +++ b/files/zh-cn/orphaned/web/api/body/body/index.html @@ -0,0 +1,87 @@ +--- +title: Body.body +slug: orphaned/Web/API/Body/body +translation_of: Web/API/Body/body +original_slug: Web/API/Body/body +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Body")}} mixin的只读getter属性 body 用于暴露其body内容的{{domxref("ReadableStream")}}(流读取)。

+ +

语法

+ +
var stream = responseInstance.body;
+ +

Value

+ +

一个 {{domxref("ReadableStream")}}.

+ +

例程

+ +

在我们的 simple stream pump 例程中我们fetch一个图片地址,使用response.body暴露响应的流,用{{domxref("body.getReader()", "ReadableStream.getReader()")}}创建一个读取器,然后将其置入第二个自定义读取流中——有效的创建了一个完全相同的图片副本。

+ +
const image = document.getElementById('target');
+
+// 请求原始图片
+fetch('./tortoise.png')
+// 取出body
+.then(response => response.body)
+.then(body => {
+  const reader = body.getReader();
+
+  return new ReadableStream({
+    start(controller) {
+      return pump();
+
+      function pump() {
+        return reader.read().then(({ done, value }) => {
+          // 读不到更多数据就关闭流
+          if (done) {
+            controller.close();
+            return;
+          }
+
+          // 将下一个数据块置入流中
+          controller.enqueue(value);
+          return pump();
+        });
+      }
+    }
+  })
+})
+.then(stream => new Response(stream))
+.then(response => response.blob())
+.then(blob => URL.createObjectURL(blob))
+.then(url => console.log(image.src = url))
+.catch(err => console.error(err));
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Fetch','#dom-body-body','body')}}{{Spec2('Fetch')}} 
+ +

浏览器兼容性

+ +
{{Compat("api.Body.body")}}
+ +

 

+ +

相关链接

+ + diff --git a/files/zh-cn/orphaned/web/api/body/bodyused/index.html b/files/zh-cn/orphaned/web/api/body/bodyused/index.html new file mode 100644 index 0000000000..a875ab79d1 --- /dev/null +++ b/files/zh-cn/orphaned/web/api/body/bodyused/index.html @@ -0,0 +1,135 @@ +--- +title: Body.bodyUsed +slug: orphaned/Web/API/Body/bodyUsed +translation_of: Web/API/Body/bodyUsed +original_slug: Web/API/Body/bodyUsed +--- +

{{APIRef("Fetch")}}{{ SeeCompatTable }}

+ +

bodyUsed 是{{domxref("Body")}} mixin中的一个只读属性。用以表示该body是否被使用过。

+ +

语法

+ +
var myBodyUsed = response.bodyUsed;
+ +

可能的值

+ +

{{domxref("Boolean")}}.

+ +

示例

+ +

在以下fetch 请求示例(运行 fetch request live)。通过{{domxref("Request.Request")}}构造器创建了一个fetch请求,来获得一张JPG图片。当fetch成功后,通过{{domxref("Blob")}} 来使用了fetch返回的资源--{{domxref("URL.createObjectURL")}}创建该资源的URL,并作为 {{htmlelement("img")}}元素的src源来显示图片。

+ +

注意:在response.blob()被调用前后,输出response.bodyUsed的差异。

+ +

HTML Content

+ +
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
+
+ +

JS Content

+ +
var myImage = document.querySelector('.my-image');
+fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg').then(function(response) {
+    console.log(response.bodyUsed);
+    var res = response.blob();
+    console.log(response.bodyUsed);
+    return res;
+}).then(function(response) {
+    var objectURL = URL.createObjectURL(response);
+    myImage.src = objectURL;
+});
+ +

{{ EmbedLiveSample('Example', '100%', '250px') }}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-bodyused','bodyUsed')}}{{Spec2('Fetch')}} 
+ +

浏览器兼容性

+ +

{{ CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatChrome(42) }} [1]
+  
{{CompatVersionUnknown}}{{ CompatGeckoDesktop(39)}} [2]{{ CompatNo }} +

29 [3]

+
{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo }}{{CompatVersionUnknown}}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

[1] Behind a preference in version 41.

+ +

[2] Behind a preference starting with version 34.

+ +

[3] Behind a preference in version 28.

+ +

See also

+ + diff --git a/files/zh-cn/orphaned/web/api/body/formdata/index.html b/files/zh-cn/orphaned/web/api/body/formdata/index.html new file mode 100644 index 0000000000..2e415887cd --- /dev/null +++ b/files/zh-cn/orphaned/web/api/body/formdata/index.html @@ -0,0 +1,123 @@ +--- +title: Body.formData() +slug: orphaned/Web/API/Body/formData +translation_of: Web/API/Body/formData +original_slug: Web/API/Body/formData +--- +
{{APIRef("Fetch")}}
+ +

 {{domxref("Body")}} 对象中的formData() 方法将 {{domxref("Response")}} 对象中的所承载的数据流读取并封装成为一个对象,该方法将返回一个 Promise  对象,该对象将产生一个{{domxref("FormData")}} 对象。

+ +
+

注意: 该方法主要与 service workers 有关. 如果客户端提交的一个表单请求被Service Worker 所截取,您可以像下述的样例一样,调用 formData() 方法来获取一个key-value 字典, 对该字典可以进行修饰, 然后将修饰后的表填提交给远端服务器 (或在本地应用)。

+
+ +

语法

+ +
response.formData()
+.then(function(formdata) {
+  // do something with your formdata
+});
+ +

参数

+ +

无。

+ +

返回值

+ +

生成 {{domxref("FormData")}}对象的{{domxref("Promise")}} 对象.

+ +

样例

+ +

待定.

+ +

详述

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-formdata','formData()')}}{{Spec2('Fetch')}} 
+ +

Browser compatibility

+ +

{{ CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support +

{{CompatChrome(60)}}

+
{{ CompatGeckoDesktop(39)}} [1]{{ CompatNo }} +

{{CompatOpera(47)}}

+
{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support +

{{CompatChrome(60)}}

+
+

{{CompatChrome(60)}}

+
{{ CompatNo }}{{ CompatNo }}{{ CompatNo }} +

{{CompatOperaMobile(47)}}

+
{{ CompatNo }}
+
+ +

[1] Behind a preference starting with version 34.

+ +

See also

+ + diff --git a/files/zh-cn/orphaned/web/api/body/index.html b/files/zh-cn/orphaned/web/api/body/index.html new file mode 100644 index 0000000000..0b12fa7259 --- /dev/null +++ b/files/zh-cn/orphaned/web/api/body/index.html @@ -0,0 +1,97 @@ +--- +title: Body +slug: orphaned/Web/API/Body +tags: + - API + - BODY + - Fetch + - bolb() + - json() + - request +translation_of: Web/API/Body +original_slug: Web/API/Body +--- +

{{ APIRef("Fetch") }}

+ +

Fetch API 中的 Body {{glossary("mixin")}} 代表响应/请求的正文,允许你声明其内容类型是什么以及应该如何处理。

+ +

Body被{{domxref("Request")}} 和{{domxref("Response")}}实现,并为这些对象提供了一个相关联的主体(字节流),一个已使用的标志(最初未设置)和一个MIME类型(最初为空字节序列)。

+ +

属性

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
一个简单的getter用于暴露一个{{domxref("ReadableStream")}}类型的主体内容。
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
一个{{domxref("Boolean")}} 值指示是否body已经被标记读取。
+
+ +

方法

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
使{{domxref("Response")}}挂起一个流操作并且在完成时读取其值,它返回一个{{domxref("Promise")}}对象,其resolve参数类型是{{domxref("ArrayBuffer")}}。此操作会将bodyUsed状态改为已使用(true)。
+
{{domxref("Body.blob()")}}
+
使{{domxref("Response")}}挂起一个流操作并且在完成时读取其值,它返回一个{{domxref("Promise")}}对象,其resolve参数类型是{{domxref("Blob")}}。此操作会将bodyUsed状态改为已使用(true)。
+
{{domxref("Body.formData()")}}
+
使{{domxref("Response")}}挂起一个流操作并且在完成时读取其值,它返回一个{{domxref("Promise")}}对象,其resolve参数类型是{{domxref("FormData")}}表单。此操作会将bodyUsed状态改为已使用(true)。
+
{{domxref("Body.json()")}}
+
使{{domxref("Response")}}挂起一个流操作并且在完成时读取其值,它返回一个{{domxref("Promise")}}对象,其resolve参数类型是使用{{jsxref("JSON")}}解析body文本的结果。此操作会将bodyUsed状态改为已使用(true)。
+
{{domxref("Body.text()")}}
+
使{{domxref("Response")}}挂起一个流操作并且在完成时读取其值,它返回一个{{domxref("Promise")}}对象,其resolve参数类型是{{domxref("USVString")}}(文本)。此操作会将bodyUsed状态改为已使用(true)。
+
+ +

范例

+ +

基本 fetch 使用实例 (查看运行效果) 中,我们使用简单的 fetch 请求获取一张图片并将其使用 {{htmlelement("img")}} 标签展示。你可能注意到当我们请求一张图片,需要使用 {{domxref("Body.blob")}} ({{domxref("Response")}} 实现 body 接口以发送正确的MIME类型给服务器进行识别。

+ +

HTML 内容

+ +
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
+
+ +

JS 内容

+ +
var myImage = document.querySelector('.my-image');
+fetch('flowers.jpg').then(function(response) {
+  return response.blob();
+}).then(function(response) {
+  var objectURL = URL.createObjectURL(response);
+  myImage.src = objectURL;
+});
+ +

你也可以使用 Response.Response() 构造函数创建自定义的 Response 对象。

+ +
const response = new Response();
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}} 
+ +

浏览器兼容情况

+ +

{{Compat("api.Body")}}

+ +

也可以看看

+ + + +

 

diff --git a/files/zh-cn/orphaned/web/api/body/json/index.html b/files/zh-cn/orphaned/web/api/body/json/index.html new file mode 100644 index 0000000000..54bd1c5c3e --- /dev/null +++ b/files/zh-cn/orphaned/web/api/body/json/index.html @@ -0,0 +1,91 @@ +--- +title: Body.json() +slug: orphaned/Web/API/Body/json +tags: + - API + - BODY + - Fetch + - JSON + - 参考 + - 方法 +translation_of: Web/API/Body/json +original_slug: Web/API/Body/json +--- +
{{APIRef("Fetch")}}
+ +
{{domxref("Body")}}  mixin 的 json() 方法接收一个 {{domxref("Response")}} 流,并将其读取完成。它返回一个 Promise,Promise 的解析 resolve 结果是将文本体解析为 {{jsxref("JSON")}}。
+ +

语法

+ +
response.json().then(data => {
+  // do something with your data
+});
+ +

参数

+ +

没有。

+ +

返回值

+ +

返回一个被解析为JSON格式的promise对象,这可以是任何可以由JSON表示的东西 - 一个object,一个array,一个string,一个number...

+ +

示例

+ +

在我们的  fetch json 示例 中(运行 fetch json live), 我们使用 {{domxref("Request.Request")}} 构造函数创建一个新的请求, 然后使用它来获取一个 .json 文件。当获取成功时,我们使用 json() 读取并解析数据,然后像预期的那样从结果对象中读取值,并将其插入到列表项中以显示我们的产品数据。

+ +
const myList = document.querySelector('ul');
+const myRequest = new Request('products.json');
+
+fetch(myRequest)
+  .then(response => response.json())
+  .then(data => {
+    for (const product of data.products) {
+      let listItem = document.createElement('li');
+      listItem.appendChild(
+        document.createElement('strong')
+      ).textContent = product.Name;
+      listItem.append(
+        ` can be found in ${
+          product.Location
+        }. Cost: `
+      );
+      listItem.appendChild(
+        document.createElement('strong')
+      ).textContent = `£${product.Price}`;
+      myList.appendChild(listItem);
+    }
+  });
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Fetch", "#dom-body-json", "Body.json()")}}{{Spec2("Fetch")}}Initial definition
+ + +

浏览器兼容性

+ + + +

{{Compat("api.Body.json")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/orphaned/web/api/body/text/index.html b/files/zh-cn/orphaned/web/api/body/text/index.html new file mode 100644 index 0000000000..320d294861 --- /dev/null +++ b/files/zh-cn/orphaned/web/api/body/text/index.html @@ -0,0 +1,86 @@ +--- +title: Body.text() +slug: orphaned/Web/API/Body/text +tags: + - API + - Fetch + - 参考 + - 方法 +translation_of: Web/API/Body/text +original_slug: Web/API/Body/text +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Body")}} mixin 的 text() 方法提供了一个可供读取的“返回流”({{domxref("Response")}} stream),并将它读取完。它返回一个包含 {{domxref("USVString")}} 对象(也就是文本)的 Promise 对象,返回结果的编码永远是 UTF-8。

+ +

语法

+ +
response.text().then(function (text) {
+  // do something with the text response
+});
+ +

参数

+ +

无。

+ +

返回值

+ +

A promise that resolves with a {{domxref("USVString")}}.

+ +

示例

+ +

在我们 fetch text example (运行 fetch text live)的案例中, 我们有一个 {{htmlelement("article")}} 元素和三个链接(储存在 myLinks 数组中),首先,遍历 myLinks 数组,并且给数组中的所有元素添加 onclick 事件监听器,当按钮被点击的时候,链接的 data-page 标识作为会参数传入 getData() 中。

+ +

当进入 getData() 函数, 我们使用 {{domxref("Request.Request","Request()")}} 构造函数创建了一个请求(Request)对象,然后,使用它获取指定的.txt的文件, 当fetch 函数执行成功, 我们使用 text() 函数来返回一个{{jsxref("USVString")}} (text) 对象,将它设置到 {{htmlelement("article")}} 对象的{{domxref("Element.innerHTML","innerHTML")}} (元素文本)中。

+ +
const myArticle = document.querySelector('article');
+const myLinks   = document.querySelectorAll('ul a');
+
+for(i = 0; i <= myLinks.length-1; i++) {
+  myLinks[i].onclick = function(e) {
+    e.preventDefault();
+    var linkData = e.target.getAttribute('data-page');
+    getData(linkData);
+  }
+};
+
+function getData(pageId) {
+  console.log(pageId);
+  const myRequest = new Request(pageId + '.txt');
+  fetch(myRequest).then(function(response) {
+    return response.text().then(function(text) {
+      myArticle.innerHTML = text;
+    });
+  });
+}
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Fetch','#dom-body-text','text()')}}{{Spec2('Fetch')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Body.text")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/body/arraybuffer/index.html b/files/zh-cn/web/api/body/arraybuffer/index.html deleted file mode 100644 index de711b01b9..0000000000 --- a/files/zh-cn/web/api/body/arraybuffer/index.html +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Body.arrayBuffer() -slug: Web/API/Body/arrayBuffer -translation_of: Web/API/Body/arrayBuffer ---- -

{{APIRef("Fetch")}}{{ SeeCompatTable() }}

- -

 {{domxref("Body")}}上的方法 arrayBuffer() 接受一个 {{domxref("Response")}} 流, 并等待其读取完成. 它返回一个 promise 实例, 并 resolve 一个 {{domxref("ArrayBuffer")}} 对象.

- -

语法

- -
response.arrayBuffer().then(function(buffer) {
-  // do something with buffer
-)};
- -

参数

- -

无。

- -

返回值

- -

A promise that resolves with an {{domxref("ArrayBuffer")}}.

- -

例子

- -

In our fetch array buffer example (run fetch array buffer live), we have a Play button. When pressed, the getData() function is run.

- -

In getData() we create a new request using the {{domxref("Request.Request")}} constructor, then use it to fetch an OGG music track. We also use {{domxref("AudioContext.createBufferSource")}} to create an audio buffer source.  When the fetch is successful, we read an {{domxref("ArrayBuffer")}} out of the response using arrayBuffer(), decode the audio data using {{domxref("AudioContext.decodeAudioData")}}, set the decoded data as the audio buffer source's buffer (source.buffer), then connect the source up to the {{domxref("AudioContext.destination")}}.

- -

Once getData() has finished running, we start the audio source playing with start(0), then disable the play button so it can't be clicked again when it is already playing (this would cause an error.)

- -
function getData() {
-  source = audioCtx.createBufferSource();
-
-  var myRequest = new Request('viper.ogg');
-
-  fetch(myRequest).then(function(response) {
-    response.arrayBuffer().then(function(buffer) {
-      audioCtx.decodeAudioData(buffer, function(decodedData) {
-        source.buffer = decodedData;
-        source.connect(audioCtx.destination);
-      });
-    });
-  });
-};
-
-// wire up buttons to stop and play audio
-
-play.onclick = function() {
-  getData();
-  source.start(0);
-  play.setAttribute('disabled', 'disabled');
-}
- -

标准

- - - - - - - - - - - - - - -
标准状态备注
{{SpecName('Fetch','#dom-body-arraybuffer','arrayBuffer()')}}{{Spec2('Fetch')}} 
- -

浏览器兼容性

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatChrome(41) }}[1]
- {{ CompatChrome(42) }}
-  
34[1]
- {{ CompatGeckoDesktop(39)}}
{{ CompatNo }} -

28[1]
- 29

-
{{ CompatNo }}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
-
- -

[1] In Chrome 42, Firefox 34 and Opera 28 support for arrayBuffer() was hidden behind a preference.

- -

参考

- - - - diff --git a/files/zh-cn/web/api/body/blob/index.html b/files/zh-cn/web/api/body/blob/index.html deleted file mode 100644 index 6b292cc7a5..0000000000 --- a/files/zh-cn/web/api/body/blob/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: Body.blob() -slug: Web/API/Body/blob -tags: - - Body.blob() -translation_of: Web/API/Body/blob ---- -

{{APIRef("Fetch")}}

- -

{{domxref("Body")}}  mixin的 blob()方法使用一个 {{domxref("Response")}} 流,并将其读取完成。它返回一个使用{{domxref("Blob")}}解决的promise。

- -

句法

- -
response.blob().then(function(myBlob) {
-  // do something with myBlob
-});
- -

参数

- -

None.

- -

返回值

- -

A promise that resolves with a {{domxref("Blob")}}.

- -

例子

- -

在我们 fetch request example (run fetch request live)中,我们使用Request.Request构造方法创建了一个新的request对象,然后使用它来获取一个JPG文件。当fetch成功的时候,我们使用blob()从response中读取一个Blob对象,并使用URL.createObjectURL 将它放入一个object URL ,然后把URL设置为img元素的src属性以显示这张图片。

- -

 

- -
var myImage = document.querySelector('img');
-
-var myRequest = new Request('flowers.jpg');
-
-fetch(myRequest)
-.then(function(response) {
-  return response.blob();
-})
-.then(function(myBlob) {
-  var objectURL = URL.createObjectURL(myBlob);
-  myImage.src = objectURL;
-});
-
- -

规范

- - - - - - - - - - - - - - -
规范状态说明
{{SpecName('Fetch','#dom-body-blob','blob()')}}{{Spec2('Fetch')}} 
- -

浏览器兼容性

- -

{{ CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatChrome(42) }} [1]
-  
{{CompatVersionUnknown}}{{ CompatGeckoDesktop(39)}} [2]{{ CompatNo }} -

29 [3]

-
{{ CompatNo }}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo }}{{CompatVersionUnknown}}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
-
- -

[1] Behind a preference in version 41.

- -

[2] Behind a preference starting with version 34.

- -

[3] Behind a preference in version 28.

- -

另见

- - diff --git a/files/zh-cn/web/api/body/body/index.html b/files/zh-cn/web/api/body/body/index.html deleted file mode 100644 index 2361cc9145..0000000000 --- a/files/zh-cn/web/api/body/body/index.html +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: Body.body -slug: Web/API/Body/body -translation_of: Web/API/Body/body ---- -
{{APIRef("Fetch")}}
- -

{{domxref("Body")}} mixin的只读getter属性 body 用于暴露其body内容的{{domxref("ReadableStream")}}(流读取)。

- -

语法

- -
var stream = responseInstance.body;
- -

Value

- -

一个 {{domxref("ReadableStream")}}.

- -

例程

- -

在我们的 simple stream pump 例程中我们fetch一个图片地址,使用response.body暴露响应的流,用{{domxref("body.getReader()", "ReadableStream.getReader()")}}创建一个读取器,然后将其置入第二个自定义读取流中——有效的创建了一个完全相同的图片副本。

- -
const image = document.getElementById('target');
-
-// 请求原始图片
-fetch('./tortoise.png')
-// 取出body
-.then(response => response.body)
-.then(body => {
-  const reader = body.getReader();
-
-  return new ReadableStream({
-    start(controller) {
-      return pump();
-
-      function pump() {
-        return reader.read().then(({ done, value }) => {
-          // 读不到更多数据就关闭流
-          if (done) {
-            controller.close();
-            return;
-          }
-
-          // 将下一个数据块置入流中
-          controller.enqueue(value);
-          return pump();
-        });
-      }
-    }
-  })
-})
-.then(stream => new Response(stream))
-.then(response => response.blob())
-.then(blob => URL.createObjectURL(blob))
-.then(url => console.log(image.src = url))
-.catch(err => console.error(err));
- -

规范

- - - - - - - - - - - - - - -
规范状态备注
{{SpecName('Fetch','#dom-body-body','body')}}{{Spec2('Fetch')}} 
- -

浏览器兼容性

- -
{{Compat("api.Body.body")}}
- -

 

- -

相关链接

- - diff --git a/files/zh-cn/web/api/body/bodyused/index.html b/files/zh-cn/web/api/body/bodyused/index.html deleted file mode 100644 index fd776b8a65..0000000000 --- a/files/zh-cn/web/api/body/bodyused/index.html +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: Body.bodyUsed -slug: Web/API/Body/bodyUsed -translation_of: Web/API/Body/bodyUsed ---- -

{{APIRef("Fetch")}}{{ SeeCompatTable }}

- -

bodyUsed 是{{domxref("Body")}} mixin中的一个只读属性。用以表示该body是否被使用过。

- -

语法

- -
var myBodyUsed = response.bodyUsed;
- -

可能的值

- -

{{domxref("Boolean")}}.

- -

示例

- -

在以下fetch 请求示例(运行 fetch request live)。通过{{domxref("Request.Request")}}构造器创建了一个fetch请求,来获得一张JPG图片。当fetch成功后,通过{{domxref("Blob")}} 来使用了fetch返回的资源--{{domxref("URL.createObjectURL")}}创建该资源的URL,并作为 {{htmlelement("img")}}元素的src源来显示图片。

- -

注意:在response.blob()被调用前后,输出response.bodyUsed的差异。

- -

HTML Content

- -
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
-
- -

JS Content

- -
var myImage = document.querySelector('.my-image');
-fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg').then(function(response) {
-    console.log(response.bodyUsed);
-    var res = response.blob();
-    console.log(response.bodyUsed);
-    return res;
-}).then(function(response) {
-    var objectURL = URL.createObjectURL(response);
-    myImage.src = objectURL;
-});
- -

{{ EmbedLiveSample('Example', '100%', '250px') }}

- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-bodyused','bodyUsed')}}{{Spec2('Fetch')}} 
- -

浏览器兼容性

- -

{{ CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatChrome(42) }} [1]
-  
{{CompatVersionUnknown}}{{ CompatGeckoDesktop(39)}} [2]{{ CompatNo }} -

29 [3]

-
{{ CompatNo }}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo }}{{CompatVersionUnknown}}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
-
- -

[1] Behind a preference in version 41.

- -

[2] Behind a preference starting with version 34.

- -

[3] Behind a preference in version 28.

- -

See also

- - diff --git a/files/zh-cn/web/api/body/formdata/index.html b/files/zh-cn/web/api/body/formdata/index.html deleted file mode 100644 index 846b6afa07..0000000000 --- a/files/zh-cn/web/api/body/formdata/index.html +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: Body.formData() -slug: Web/API/Body/formData -translation_of: Web/API/Body/formData ---- -
{{APIRef("Fetch")}}
- -

 {{domxref("Body")}} 对象中的formData() 方法将 {{domxref("Response")}} 对象中的所承载的数据流读取并封装成为一个对象,该方法将返回一个 Promise  对象,该对象将产生一个{{domxref("FormData")}} 对象。

- -
-

注意: 该方法主要与 service workers 有关. 如果客户端提交的一个表单请求被Service Worker 所截取,您可以像下述的样例一样,调用 formData() 方法来获取一个key-value 字典, 对该字典可以进行修饰, 然后将修饰后的表填提交给远端服务器 (或在本地应用)。

-
- -

语法

- -
response.formData()
-.then(function(formdata) {
-  // do something with your formdata
-});
- -

参数

- -

无。

- -

返回值

- -

生成 {{domxref("FormData")}}对象的{{domxref("Promise")}} 对象.

- -

样例

- -

待定.

- -

详述

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-formdata','formData()')}}{{Spec2('Fetch')}} 
- -

Browser compatibility

- -

{{ CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support -

{{CompatChrome(60)}}

-
{{ CompatGeckoDesktop(39)}} [1]{{ CompatNo }} -

{{CompatOpera(47)}}

-
{{ CompatNo }}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support -

{{CompatChrome(60)}}

-
-

{{CompatChrome(60)}}

-
{{ CompatNo }}{{ CompatNo }}{{ CompatNo }} -

{{CompatOperaMobile(47)}}

-
{{ CompatNo }}
-
- -

[1] Behind a preference starting with version 34.

- -

See also

- - diff --git a/files/zh-cn/web/api/body/index.html b/files/zh-cn/web/api/body/index.html deleted file mode 100644 index d6094d90ab..0000000000 --- a/files/zh-cn/web/api/body/index.html +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Body -slug: Web/API/Body -tags: - - API - - BODY - - Fetch - - bolb() - - json() - - request -translation_of: Web/API/Body ---- -

{{ APIRef("Fetch") }}

- -

Fetch API 中的 Body {{glossary("mixin")}} 代表响应/请求的正文,允许你声明其内容类型是什么以及应该如何处理。

- -

Body被{{domxref("Request")}} 和{{domxref("Response")}}实现,并为这些对象提供了一个相关联的主体(字节流),一个已使用的标志(最初未设置)和一个MIME类型(最初为空字节序列)。

- -

属性

- -
-
{{domxref("Body.body")}} {{readonlyInline}}
-
一个简单的getter用于暴露一个{{domxref("ReadableStream")}}类型的主体内容。
-
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
-
一个{{domxref("Boolean")}} 值指示是否body已经被标记读取。
-
- -

方法

- -
-
{{domxref("Body.arrayBuffer()")}}
-
使{{domxref("Response")}}挂起一个流操作并且在完成时读取其值,它返回一个{{domxref("Promise")}}对象,其resolve参数类型是{{domxref("ArrayBuffer")}}。此操作会将bodyUsed状态改为已使用(true)。
-
{{domxref("Body.blob()")}}
-
使{{domxref("Response")}}挂起一个流操作并且在完成时读取其值,它返回一个{{domxref("Promise")}}对象,其resolve参数类型是{{domxref("Blob")}}。此操作会将bodyUsed状态改为已使用(true)。
-
{{domxref("Body.formData()")}}
-
使{{domxref("Response")}}挂起一个流操作并且在完成时读取其值,它返回一个{{domxref("Promise")}}对象,其resolve参数类型是{{domxref("FormData")}}表单。此操作会将bodyUsed状态改为已使用(true)。
-
{{domxref("Body.json()")}}
-
使{{domxref("Response")}}挂起一个流操作并且在完成时读取其值,它返回一个{{domxref("Promise")}}对象,其resolve参数类型是使用{{jsxref("JSON")}}解析body文本的结果。此操作会将bodyUsed状态改为已使用(true)。
-
{{domxref("Body.text()")}}
-
使{{domxref("Response")}}挂起一个流操作并且在完成时读取其值,它返回一个{{domxref("Promise")}}对象,其resolve参数类型是{{domxref("USVString")}}(文本)。此操作会将bodyUsed状态改为已使用(true)。
-
- -

范例

- -

基本 fetch 使用实例 (查看运行效果) 中,我们使用简单的 fetch 请求获取一张图片并将其使用 {{htmlelement("img")}} 标签展示。你可能注意到当我们请求一张图片,需要使用 {{domxref("Body.blob")}} ({{domxref("Response")}} 实现 body 接口以发送正确的MIME类型给服务器进行识别。

- -

HTML 内容

- -
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
-
- -

JS 内容

- -
var myImage = document.querySelector('.my-image');
-fetch('flowers.jpg').then(function(response) {
-  return response.blob();
-}).then(function(response) {
-  var objectURL = URL.createObjectURL(response);
-  myImage.src = objectURL;
-});
- -

你也可以使用 Response.Response() 构造函数创建自定义的 Response 对象。

- -
const response = new Response();
-
- -

规范

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}} 
- -

浏览器兼容情况

- -

{{Compat("api.Body")}}

- -

也可以看看

- - - -

 

diff --git a/files/zh-cn/web/api/body/json/index.html b/files/zh-cn/web/api/body/json/index.html deleted file mode 100644 index 58583dddf0..0000000000 --- a/files/zh-cn/web/api/body/json/index.html +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: Body.json() -slug: Web/API/Body/json -tags: - - API - - BODY - - Fetch - - JSON - - 参考 - - 方法 -translation_of: Web/API/Body/json ---- -
{{APIRef("Fetch")}}
- -
{{domxref("Body")}}  mixin 的 json() 方法接收一个 {{domxref("Response")}} 流,并将其读取完成。它返回一个 Promise,Promise 的解析 resolve 结果是将文本体解析为 {{jsxref("JSON")}}。
- -

语法

- -
response.json().then(data => {
-  // do something with your data
-});
- -

参数

- -

没有。

- -

返回值

- -

返回一个被解析为JSON格式的promise对象,这可以是任何可以由JSON表示的东西 - 一个object,一个array,一个string,一个number...

- -

示例

- -

在我们的  fetch json 示例 中(运行 fetch json live), 我们使用 {{domxref("Request.Request")}} 构造函数创建一个新的请求, 然后使用它来获取一个 .json 文件。当获取成功时,我们使用 json() 读取并解析数据,然后像预期的那样从结果对象中读取值,并将其插入到列表项中以显示我们的产品数据。

- -
const myList = document.querySelector('ul');
-const myRequest = new Request('products.json');
-
-fetch(myRequest)
-  .then(response => response.json())
-  .then(data => {
-    for (const product of data.products) {
-      let listItem = document.createElement('li');
-      listItem.appendChild(
-        document.createElement('strong')
-      ).textContent = product.Name;
-      listItem.append(
-        ` can be found in ${
-          product.Location
-        }. Cost: `
-      );
-      listItem.appendChild(
-        document.createElement('strong')
-      ).textContent = `£${product.Price}`;
-      myList.appendChild(listItem);
-    }
-  });
- -

规范

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("Fetch", "#dom-body-json", "Body.json()")}}{{Spec2("Fetch")}}Initial definition
- - -

浏览器兼容性

- - - -

{{Compat("api.Body.json")}}

- -

相关链接

- - diff --git a/files/zh-cn/web/api/body/text/index.html b/files/zh-cn/web/api/body/text/index.html deleted file mode 100644 index 4a67985fd9..0000000000 --- a/files/zh-cn/web/api/body/text/index.html +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: Body.text() -slug: Web/API/Body/text -tags: - - API - - Fetch - - 参考 - - 方法 -translation_of: Web/API/Body/text ---- -
{{APIRef("Fetch")}}
- -

{{domxref("Body")}} mixin 的 text() 方法提供了一个可供读取的“返回流”({{domxref("Response")}} stream),并将它读取完。它返回一个包含 {{domxref("USVString")}} 对象(也就是文本)的 Promise 对象,返回结果的编码永远是 UTF-8。

- -

语法

- -
response.text().then(function (text) {
-  // do something with the text response
-});
- -

参数

- -

无。

- -

返回值

- -

A promise that resolves with a {{domxref("USVString")}}.

- -

示例

- -

在我们 fetch text example (运行 fetch text live)的案例中, 我们有一个 {{htmlelement("article")}} 元素和三个链接(储存在 myLinks 数组中),首先,遍历 myLinks 数组,并且给数组中的所有元素添加 onclick 事件监听器,当按钮被点击的时候,链接的 data-page 标识作为会参数传入 getData() 中。

- -

当进入 getData() 函数, 我们使用 {{domxref("Request.Request","Request()")}} 构造函数创建了一个请求(Request)对象,然后,使用它获取指定的.txt的文件, 当fetch 函数执行成功, 我们使用 text() 函数来返回一个{{jsxref("USVString")}} (text) 对象,将它设置到 {{htmlelement("article")}} 对象的{{domxref("Element.innerHTML","innerHTML")}} (元素文本)中。

- -
const myArticle = document.querySelector('article');
-const myLinks   = document.querySelectorAll('ul a');
-
-for(i = 0; i <= myLinks.length-1; i++) {
-  myLinks[i].onclick = function(e) {
-    e.preventDefault();
-    var linkData = e.target.getAttribute('data-page');
-    getData(linkData);
-  }
-};
-
-function getData(pageId) {
-  console.log(pageId);
-  const myRequest = new Request(pageId + '.txt');
-  fetch(myRequest).then(function(response) {
-    return response.text().then(function(text) {
-      myArticle.innerHTML = text;
-    });
-  });
-}
- -

规范

- - - - - - - - - - - - - - -
规范状态备注
{{SpecName('Fetch','#dom-body-text','text()')}}{{Spec2('Fetch')}}
- -

浏览器兼容性

- - - -

{{Compat("api.Body.text")}}

- -

See also

- - diff --git a/files/zh-tw/_redirects.txt b/files/zh-tw/_redirects.txt index 3a3feb0fb4..b3d83e932c 100644 --- a/files/zh-tw/_redirects.txt +++ b/files/zh-tw/_redirects.txt @@ -543,6 +543,8 @@ /zh-TW/docs/Using_files_from_web_applications /zh-TW/docs/Web/API/File/Using_files_from_web_applications /zh-TW/docs/Using_geolocation /zh-TW/docs/Web/API/Geolocation_API /zh-TW/docs/Web/API/Ambient_Light_Events /zh-TW/docs/orphaned/Web/API/Ambient_Light_Events +/zh-TW/docs/Web/API/Body /zh-TW/docs/orphaned/Web/API/Body +/zh-TW/docs/Web/API/Body/json /zh-TW/docs/orphaned/Web/API/Body/json /zh-TW/docs/Web/API/Canvas_API/Drawing_graphics_with_canvas /zh-TW/docs/conflicting/Web/API/Canvas_API/Tutorial /zh-TW/docs/Web/API/Canvas_API/Tutorial/基礎動畫 /zh-TW/docs/Web/API/Canvas_API/Tutorial/Basic_animations /zh-TW/docs/Web/API/Canvas_API/Tutorial/最佳化_canvas /zh-TW/docs/Web/API/Canvas_API/Tutorial/Optimizing_canvas diff --git a/files/zh-tw/_wikihistory.json b/files/zh-tw/_wikihistory.json index eadfe8d04c..b02f83fe11 100644 --- a/files/zh-tw/_wikihistory.json +++ b/files/zh-tw/_wikihistory.json @@ -2922,19 +2922,6 @@ "flyinglimao" ] }, - "Web/API/Body": { - "modified": "2020-10-15T22:10:19.507Z", - "contributors": [ - "RickBrown" - ] - }, - "Web/API/Body/json": { - "modified": "2020-10-15T22:10:18.425Z", - "contributors": [ - "xstar", - "eyeccc" - ] - }, "Web/API/CSSStyleDeclaration": { "modified": "2019-03-23T22:30:39.103Z", "contributors": [ @@ -8638,6 +8625,19 @@ "MashKao" ] }, + "orphaned/Web/API/Body": { + "modified": "2020-10-15T22:10:19.507Z", + "contributors": [ + "RickBrown" + ] + }, + "orphaned/Web/API/Body/json": { + "modified": "2020-10-15T22:10:18.425Z", + "contributors": [ + "xstar", + "eyeccc" + ] + }, "orphaned/Web/API/ChildNode": { "modified": "2019-03-23T22:30:29.724Z", "contributors": [ diff --git a/files/zh-tw/orphaned/web/api/body/index.html b/files/zh-tw/orphaned/web/api/body/index.html new file mode 100644 index 0000000000..0794ac997e --- /dev/null +++ b/files/zh-tw/orphaned/web/api/body/index.html @@ -0,0 +1,100 @@ +--- +title: Body +slug: orphaned/Web/API/Body +tags: + - API + - BODY + - Experimental + - Fetch + - Fetch API + - Interface + - NeedsTranslation + - Reference + - TopicStub + - request +translation_of: Web/API/Body +original_slug: Web/API/Body +--- +
{{ APIRef("Fetch") }}
+ +

The Body {{glossary("mixin")}} of the Fetch API represents the body of the response/request, allowing you to declare what its content type is and how it should be handled.

+ +

Body is implemented by both {{domxref("Request")}} and {{domxref("Response")}}. This provides these objects with an associated body (a stream), a used flag (initially unset), and a MIME type (initially the empty byte sequence).

+ +

Properties

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
A simple getter used to expose a {{domxref("ReadableStream")}} of the body contents.
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
A {{domxref("Boolean")}} that indicates whether the body has been read.
+
+ +

Methods

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{domxref("ArrayBuffer")}}.
+
{{domxref("Body.blob()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("Blob")}}.
+
{{domxref("Body.formData()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("FormData")}} object.
+
{{domxref("Body.json()")}}
+
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")}}.
+
{{domxref("Body.text()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("USVString")}} (text). The response is always decoded using UTF-8.
+
+ +

Examples

+ +

The example below uses a simple fetch call to grab an image and display it in an {{htmlelement("img")}} tag. You'll notice that since we are requesting an image, we need to run {{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} implements body) to give the response its correct MIME type.

+ +

HTML Content

+ +
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
+
+ +

JS Content

+ +
var myImage = document.querySelector('.my-image');
+fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
+	.then(res => res.blob())
+	.then(res => {
+		var objectURL = URL.createObjectURL(res);
+		myImage.src = objectURL;
+});
+ +

{{ EmbedLiveSample('Examples', '100%', '250px') }}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.Body")}}

+ +

See also

+ + + +

 

diff --git a/files/zh-tw/orphaned/web/api/body/json/index.html b/files/zh-tw/orphaned/web/api/body/json/index.html new file mode 100644 index 0000000000..44d12f70fa --- /dev/null +++ b/files/zh-tw/orphaned/web/api/body/json/index.html @@ -0,0 +1,74 @@ +--- +title: Body.json() +slug: orphaned/Web/API/Body/json +translation_of: Web/API/Body/json +original_slug: Web/API/Body/json +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Body")}} mixin 的 json() 會拿 {{domxref("Response")}} stream 並完整地讀取他。它會回傳一個能夠實現 (resolve) 把回傳的結果的 body text 解析成 {{jsxref("JSON")}} 型別的 Promise。

+ +

語法

+ +
response.json().then(function(data) {
+  // do something with your data
+});
+ +

參數

+ +

None.

+ +

回傳

+ +

一個能夠實現 (resolve) 把回傳的結果的 body text 解析成 JSON 型別的 Promise。這可以是任何能夠被 JSON 呈現的資料型別 — 物件 (object), 陣列 (array), 字串 (string), 數字 (number)...

+ +

範例

+ +

在我們的範例 fetch json example (run fetch json live) 中,我們用 constructor {{domxref("Request.Request")}} 產生一個新的請求,並且用它去取回 .json 檔案。 當成功取回 (fetch) 時,我們使用 json() 去讀取跟解析資料,然後依照我們期待的把回傳的結果物件 (resulting objects) 裡讀取到的數值存入 list 中藉以顯示我們的產品資料。

+ +
var myList = document.querySelector('ul');
+
+var myRequest = new Request('products.json');
+
+fetch(myRequest)
+  .then(function(response) { return response.json(); })
+  .then(function(data) {
+    for (var i = 0; i < data.products.length; i++) {
+      var listItem = document.createElement('li');
+      listItem.innerHTML = '<strong>' + data.products[i].Name + '</strong> can be found in ' +
+                           data.products[i].Location +
+                           '. Cost: <strong>£' + data.products[i].Price + '</strong>';
+      myList.appendChild(listItem);
+    }
+  });
+ +

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-json','json()')}}{{Spec2('Fetch')}}
+ +

瀏覽器相容性

+ + + +

{{Compat("api.Body.json")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/api/body/index.html b/files/zh-tw/web/api/body/index.html deleted file mode 100644 index 82ba54e53d..0000000000 --- a/files/zh-tw/web/api/body/index.html +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Body -slug: Web/API/Body -tags: - - API - - BODY - - Experimental - - Fetch - - Fetch API - - Interface - - NeedsTranslation - - Reference - - TopicStub - - request -translation_of: Web/API/Body ---- -
{{ APIRef("Fetch") }}
- -

The Body {{glossary("mixin")}} of the Fetch API represents the body of the response/request, allowing you to declare what its content type is and how it should be handled.

- -

Body is implemented by both {{domxref("Request")}} and {{domxref("Response")}}. This provides these objects with an associated body (a stream), a used flag (initially unset), and a MIME type (initially the empty byte sequence).

- -

Properties

- -
-
{{domxref("Body.body")}} {{readonlyInline}}
-
A simple getter used to expose a {{domxref("ReadableStream")}} of the body contents.
-
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
-
A {{domxref("Boolean")}} that indicates whether the body has been read.
-
- -

Methods

- -
-
{{domxref("Body.arrayBuffer()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{domxref("ArrayBuffer")}}.
-
{{domxref("Body.blob()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("Blob")}}.
-
{{domxref("Body.formData()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("FormData")}} object.
-
{{domxref("Body.json()")}}
-
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")}}.
-
{{domxref("Body.text()")}}
-
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("USVString")}} (text). The response is always decoded using UTF-8.
-
- -

Examples

- -

The example below uses a simple fetch call to grab an image and display it in an {{htmlelement("img")}} tag. You'll notice that since we are requesting an image, we need to run {{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} implements body) to give the response its correct MIME type.

- -

HTML Content

- -
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
-
- -

JS Content

- -
var myImage = document.querySelector('.my-image');
-fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
-	.then(res => res.blob())
-	.then(res => {
-		var objectURL = URL.createObjectURL(res);
-		myImage.src = objectURL;
-});
- -

{{ EmbedLiveSample('Examples', '100%', '250px') }}

- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}} 
- -

Browser compatibility

- - - -

{{Compat("api.Body")}}

- -

See also

- - - -

 

diff --git a/files/zh-tw/web/api/body/json/index.html b/files/zh-tw/web/api/body/json/index.html deleted file mode 100644 index 70085afff7..0000000000 --- a/files/zh-tw/web/api/body/json/index.html +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Body.json() -slug: Web/API/Body/json -translation_of: Web/API/Body/json ---- -
{{APIRef("Fetch")}}
- -

{{domxref("Body")}} mixin 的 json() 會拿 {{domxref("Response")}} stream 並完整地讀取他。它會回傳一個能夠實現 (resolve) 把回傳的結果的 body text 解析成 {{jsxref("JSON")}} 型別的 Promise。

- -

語法

- -
response.json().then(function(data) {
-  // do something with your data
-});
- -

參數

- -

None.

- -

回傳

- -

一個能夠實現 (resolve) 把回傳的結果的 body text 解析成 JSON 型別的 Promise。這可以是任何能夠被 JSON 呈現的資料型別 — 物件 (object), 陣列 (array), 字串 (string), 數字 (number)...

- -

範例

- -

在我們的範例 fetch json example (run fetch json live) 中,我們用 constructor {{domxref("Request.Request")}} 產生一個新的請求,並且用它去取回 .json 檔案。 當成功取回 (fetch) 時,我們使用 json() 去讀取跟解析資料,然後依照我們期待的把回傳的結果物件 (resulting objects) 裡讀取到的數值存入 list 中藉以顯示我們的產品資料。

- -
var myList = document.querySelector('ul');
-
-var myRequest = new Request('products.json');
-
-fetch(myRequest)
-  .then(function(response) { return response.json(); })
-  .then(function(data) {
-    for (var i = 0; i < data.products.length; i++) {
-      var listItem = document.createElement('li');
-      listItem.innerHTML = '<strong>' + data.products[i].Name + '</strong> can be found in ' +
-                           data.products[i].Location +
-                           '. Cost: <strong>£' + data.products[i].Price + '</strong>';
-      myList.appendChild(listItem);
-    }
-  });
- -

規範

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-json','json()')}}{{Spec2('Fetch')}}
- -

瀏覽器相容性

- - - -

{{Compat("api.Body.json")}}

- -

參見

- - -- cgit v1.2.3-54-g00ecf