From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- files/zh-tw/web/api/body/json/index.html | 73 ++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 files/zh-tw/web/api/body/json/index.html (limited to 'files/zh-tw/web/api/body/json') diff --git a/files/zh-tw/web/api/body/json/index.html b/files/zh-tw/web/api/body/json/index.html new file mode 100644 index 0000000000..70085afff7 --- /dev/null +++ b/files/zh-tw/web/api/body/json/index.html @@ -0,0 +1,73 @@ +--- +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