Christian-health / StudyNote2017

2017年学习笔记
0 stars 0 forks source link

Response回复详解 #29

Open Christian-health opened 6 years ago

Christian-health commented 6 years ago

image
image
image

https://developer.mozilla.org/en-US/docs/Web/API/Body/text

Christian-health commented 6 years ago

Body 详解

https://developer.mozilla.org/en-US/docs/Web/API/Body
The Body 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 Request and 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). Body由Request和Response实现。 这为这些对象提供了: 一个关联的主体(一个流), 一个使用的标志(最初未设置), 一个MIME类型(最初是空字节序列)

Properties

属性

Body.body (Read only)

Body.body只读

A simple getter used to expose a ReadableStream of the body contents. 一个简单的getter用于显示正文内容的ReadableStream。

Body.bodyUsed (Read only)

Body.bodyUsed只读

A Boolean that indicates whether the body has been read. 指示是否已经读取正文的布尔值。

Methods

Body.arrayBuffer()

Takes a Response stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer. 采取响应流并将其读取完成。 它返回一个用ArrayBuffer解决的承诺。

Body.blob()

Takes a Response stream and reads it to completion. It returns a promise that resolves with a Blob.

Body.formData()

采取响应流并将其读取完成。 它返回一个用Blob解决的承诺。 Takes a Response stream and reads it to completion. It returns a promise that resolves with a FormData object. 采取响应流并将其读取完成。 它返回一个用FormData对象来解析的promise。

Body.json()

Takes a Response stream and reads it to completion. It returns a promise that resolves with a JSON object. 采取响应流并将其读取完成。 它返回一个用JSON对象解析的promise。

Body.text()

Takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString (text). 采取响应流并将其读取完成。 它返回一个用USVString(文本)解决的承诺。

Examples

The example below uses a simple fetch call to grab an image and display it in an tag. You'll notice that since we are requesting an image, we need to run Body.blob() (Response implements body) to give the response its correct MIME type. 下面的示例使用一个简单的获取调用来获取图像并将其显示在标记中。 你会注意到,因为我们正在请求一个图像,我们需要运行Body.blob()(Response implements body)来为响应提供正确的MIME类型。

<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
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;
});
Christian-health commented 6 years ago

Body.bodyUsed

The bodyUsed read-only property of the Body mixin contains a Boolean that indicates whether the body has been read yet. body 混合体的bodyUsed只读属性包含一个布尔值,指示主体是否已被读取。

Syntax

var myBodyUsed = response.bodyUsed;

Value

A Boolean.

Example

In our fetch request example (run fetch request live), we create a new request using the Request.Request constructor, then use it to fetch a JPG. When the fetch is successful, we read a Blob out of the response using blob(), put it into an object URL using URL.createObjectURL, and then set that URL as the source of an element to display the image. 在我们的fetch请求示例(运行fetch request)中,我们使用Request.Request构造函数创建一个新的请求,然后使用它来获取JPG。 当获取成功时,我们使用blob()从响应中读取Blob,使用URL.createObjectURL将其放入一个对象URL中,然后将该URL设置为元素的来源以显示图像。

Notice that we log response.bodyUsed to the console once before the response.blob() call and once after. This returns false before and true afterwards, as at that point the body has been read. 请注意,我们在response.blob()调用之前记录response.bodyUsed到控制台一次。 这之前返回false,之后返回true,因为此时已经读取了body。

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);// 打印出false
    var res = response.blob();
    console.log(response.bodyUsed);// 打印出true
    return res;
}).then(function(response) {
    var objectURL = URL.createObjectURL(response);
    myImage.src = objectURL;
});
Christian-health commented 6 years ago

Method

Body.arrayBuffer()

The arrayBuffer() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer. Body混合体的arrayBuffer()方法接受一个Response流并读取完成。 它返回一个用ArrayBuffer解决的承诺。

Syntax

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

Parameters

None.

Returns

A promise that resolves with an ArrayBuffer. 用ArrayBuffer解决的承诺。

Example

In our fetch array buffer example (run fetch array buffer live), we have a Play button. When pressed, the getData() function is run. 在我们获取数组缓冲例如(RUN获取数组缓冲现场),我们有一个播放按钮。 按下时,运行getData()函数。 In getData() we create a new request using the Request.Request constructor, then use it to fetch an OGG music track. We also use AudioContext.createBufferSource to create an audio buffer source. When the fetch is successful, we read an ArrayBuffer out of the response using arrayBuffer(), decode the audio data using AudioContext.decodeAudioData, set the decoded data as the audio buffer source's buffer (source.buffer), then connect the source up to the AudioContext.destination. 在getData()中,我们使用Request.Request构造函数创建一个新的请求,然后用它来获取OGG音乐曲目。 我们也使用AudioContext.createBufferSource来创建一个音频缓冲源。 当获取成功时,我们使用arrayBuffer()从响应中读取ArrayBuffer,使用AudioContext.decodeAudioData解码音频数据,将解码数据设置为音频缓冲区源缓冲区(source.buffer),然后将源连接到 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.) 一旦getData()完成运行,我们开始播放音频源的开始(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');
}
Christian-health commented 6 years ago

Body.blob()

The blob() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with a Blob. Body 混合体的blob()方法接收一个Response流并读取完成。 它返回一个用Blob解决的承诺。

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

Parameters

None.

Returns

A promise that resolves with a Blob. 使用Blob解决的承诺。

Example

In our fetch request example (run fetch request live), we create a new request using the Request.Request constructor, then use it to fetch a JPG. When the fetch is successful, we read a Blob out of the response using blob(), put it into an object URL using URL.createObjectURL, and then set that URL as the source of an element to display the image. 在我们的fetch请求示例(运行fetch request)中,我们使用Request.Request构造函数创建一个新的请求,然后使用它来获取JPG。 当获取成功时,我们使用blob()从响应中读取Blob,使用URL.createObjectURL将其放入一个对象URL中,然后将该URL设置为元素的来源以显示图像。

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;
});
Christian-health commented 6 years ago

Body.formData()

The formData() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with a FormData object.

Body混合体的formData()方法接受一个Response流并读取完成。 它返回一个用FormData对象来解析的promise。

Syntax

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

Parameters

None.

Return value

A Promise that resolves with a FormData object. 用FormData对象解决的Promise

Christian-health commented 6 years ago

Body.json()

The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON. Body混合体的json()方法接收一个Response流并读取完成。 它返回一个承诺,将解析正文文本的结果解析为JSON。

Syntax

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

Parameters

None.

Returns

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... 解析正文文本为JSON的结果。 这可以是任何可以由JSON表示的东西 - Object,数组,字符串,数字...

Example

In our fetch json example (run fetch json live), we create a new request using the 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. 在我们的fetch json示例中(运行fetch json live),我们使用Request.Request构造函数创建一个新的请求,然后用它来获取一个.json文件。 当获取成功时,我们使用json()读取和解析数据,然后按照您的期望从结果对象中读取值,并将其插入到列表项中以显示我们的产品数据。

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);
    }
  });
Christian-health commented 6 years ago

Body.text()

The text() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString object (text).

Syntax

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

Parameters

None.

Returns A promise that resolves with a USVString. 用USVString解决的承诺。

Example

In our fetch text example (run fetch text live), we have an

element and three links (stored in the myLinks array.) First, we loop through all of these and give each one an onclick event handler so that the getData() function is run — with the link's data-page identifier passed to it as an argument — when one of the links is clicked. 在我们的获取文本示例中(运行获取文本),我们有一个
元素和三个链接(存储在myLinks数组中)。首先,我们遍历所有这些,并给每一个onclick事件处理程序,使得getData ()函数运行 - 链接的数据页面标识符作为参数传递给它 - 当其中一个链接被点击。
When getData() is run, we create a new request using the Request() constructor, then use it to fetch a specific .txt file. When the fetch is successful, we read a USVString (text) object out of the response using text(), then set the innerHTML of the
element equal to the text object. 当运行getData()时,我们使用Request()构造函数创建一个新的请求,然后使用它来获取特定的.txt文件。 当获取成功时,我们使用text()从响应中读取USVString(text)对象,然后将
元素的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;
    });
  });
}
Christian-health commented 6 years ago

FormData 对象的使用

FormData 对象资料:(可以独立于表单使用
https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects

Christian-health commented 6 years ago

BLOB (binary large object),二进制大对象

https://developer.mozilla.org/zh-CN/docs/Web/API/Blob

Christian-health commented 6 years ago

USVString

https://developer.mozilla.org/zh-CN/docs/Web/API/USVString