綜合示範:抓取資料並顯示


Posted by tzutzu858 on 2020-08-19

首先確定用 ajax 可以拿到資料

step1 : 刻版面
step2 : 用 innerHTML
step3 : 把資料動態換成 server 上面拿下來的動態資料,最後 append 到畫面上

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>資料顯現出來</title>
    <style>
        body {
            font-size: 38px;
        }

        .profile {
            border: 1px solid #333;
            margin-top: 20px;
            display: inline-flex;
            align-items: center;
        }

        .profile_name {
            margin: 0px 10px;
        }
    </style>
</head>

<body>
    <div class='app'>
    </div>

    <script>
        const request = new XMLHttpRequest()
        const container = document.querySelector('.app')
        request.addEventListener('load', function () {
            if (request.status >= 200 && request.status < 400) {
                const response = request.responseText
                const json = JSON.parse(response)
                const users = json.data
                for (let i = 0; i < users.length; i++) {
                    const div = document.createElement('div')
                    div.classList.add('profile')
                    div.innerHTML =`
                         <div class='profile_name'>${users[i].first_name} ${users[i].last_name}</div>
                         <img class='profile_img' src='${users[i].avatar}'/>
                         `
                    container.appendChild(div)
                }
            } else {
                console.log('err')
            }
        })
        request.onerror = function () {
            console.log('error')
        }
        request.open('GET', 'https://reqres.in/api/users', true)
        request.send()
    </script>
</body>

</html>

成功把資料顯現出來


補充 :

  • 小地方大學問:內容產生的地方在 client 還是 server

client side rendering

用 javascript 去 rander 這個畫面,用 javascript 去動態新增內容。
所以檢視原始碼看不到任何東西,因為是動態產生資料
缺點是用搜尋引擎看這頁面是沒有任何內容

JS 總結 :

  1. 用 JS 改變 UI
  2. 用 JS 去監聽一個事件
  3. 和 server 交換資料









Related Posts

筆記、[ALG101] 看懂題目+寫程式

筆記、[ALG101] 看懂題目+寫程式

text CSS 屬性 補

text CSS 屬性 補

[Linux] wsl系統遷移

[Linux] wsl系統遷移


Comments