iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 28
0
自我挑戰組

不用前端框架 手把手打造基礎SPA網站系列 第 28

[DAY28]番外篇-使用fetch發送請求

大家好,距離完賽越來越近了,過完最後一天的雙十連假,心情也開始憂鬱了QQ,還好本系列複雜的文章差不多都介紹完了,終於不用再熬夜了。

什麼是fetch?

今天要來聊聊的是Javascript原生請求資料的方式fetch。記得以前還沒有fetch時,得透過XMLHttpRequest或是jQuery的AJAX,自從有了fetch就再也回不去了,首先我們去MDN看看fetch的說明:

Fetch API 提供了一種 JavaScript Interface 來操作 HTTP pipeline,比方 request 和 response。同時它也提供了 global 的 fetch() method,使得在網路上非同步地 fetch resources 這件事變得簡單易懂

另外小弟認為fetch具有以下特點:

  • 原生javascript語法,不需引入其他library
  • 用法類似jQuery的Ajax,無痛接軌
  • Promise語法可以避免callback hell的情形

目前各個瀏覽器也幾乎都有支援,除了你知道的IE (下圖截自caniuse.com)

fetch如何使用?

直接來看看怎麼操作:

fetch('/src/json/product.json', {})
    .then((res) => res.json())
    .then((data) => {
            console.log(data)
        })
    })

查閱MDN說明,fetch第一個參數放入請求來源的URI,第二個參數是選用的,可以傳送一個 init Object 來設定 request。

由於fetch本身是Promise物件,需要搭配then進行下一步的處理。由於在第一個then會拿到Promise結果,需要對Body的資料類型進行resolved 後才能取得資料,以下是resolve的方法(詳細可查看MDN):

  • arrayBuffer()
  • blob()
  • json()
  • text()
  • formData()

用fetch處理GET請求

這邊我們直接演示一個範例吧,用前天建立的商品頁Product.js來做出商品列表(請求的範例JSON放在這裡):

src/pages/Product.js:

import { App } from './App'
 
export const Product = {
    mount: () => {
        fetch('/src/json/product.json', {})
            .then((res) => res.json())
            .then((data) => {
                const productList = document.querySelector('#productList')
 
                data.result.forEach((item) => {
                    productList.innerHTML += `
                        <div class="col-md-4 mb-3">
                            <div class="card">
                                <div class="overflow-hidden" style="height:150px"><img src="${item.image}" class="img-fluid" alt="${item.name}" style="width:100%"></div>
                                <div class="card-body">
                                    <h5 class="font-weight-bold">${item.name}</h5>
                                    <h6>$ ${item.price}</h6>
                                    <h6>${item.desc}</h6>
                                    <a href="#/product/detail/${item.id}" class="btn btn-block btn-primary">
                                        <i class="fas fa-shopping-cart"></i> 購買
                                    </a>
                                </div>
                            </div>
                        </div>
                    `
                })
            })
    },
    render: (props) => {
        const content = `            
            <div class="container">
                <h3>${props.category}</h3>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="#">Home</a></li>
                        <li class="breadcrumb-item active">${props.category}</li>
                    </ol>
                </nav>
                <div id="productList" class="row"></div>
            </div>
        `
 
        return App.render(content)
    },
}

這裡在mount方法中使用fetch的GET方法來請求資料,且不帶入第二個參數。解析Promise物件資料,並將資料內容轉為JSON格式做處理,商品圖片已轉為base64字串,加上其餘資料使用forEach依序塞入HTML,結果會像下面這樣:

以上就是使用fetch來請求資料,這裡暫時告個段落,明天再來進一步談談fetch的POST請求,我們明天見!

參考資料:
鐵人賽:ES6 原生 Fetch 遠端資料方法


上一篇
[DAY27]番外篇-用Javascript在SPA中實做Bootstrap Modal 之二
下一篇
[DAY29]番外篇-使用fetch傳送表單資料
系列文
不用前端框架 手把手打造基礎SPA網站30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言