iT邦幫忙

2024 iThome 鐵人賽

DAY 7
0

Ajax Type Ahead

從固定的json檔案中得到資料,將它渲染在畫面中.並且結合搜尋的功能,讓使用者搜尋關鍵字,找到符合條件的資料.以上是這次的練習介紹.

https://ithelp.ithome.com.tw/upload/images/20240916/20169174FLfhK2tOLN.png

以及個人codepen

技巧點

1. fetch()

fetch是一個用來操作遠端資料,直接在()內帶入你要獲取的連結即可.
會回傳一個promise來處理回應,成功的話then會處理下一步、錯誤的情況會進入catch.

fetch(api)
  .then((res) => res.json()) // res為一個可讀的物件,需要經由其他方法轉為可使用的資料.
  .then((data) => {
    console.log(data);
  })
  .catch((err) => console.error(err));
  • fetch的過程中,如果發生promise reject的狀況,只有網路錯誤或是其他中斷request的行為.會讓promise進入到catch.其餘都會resolve,會進入到then的階段.
  • 那要判斷是否有成功得到資料,就只能從res中的ok的狀態去判斷,這個ok的狀態會回傳true或fals.如下:
fetch(api) // 假設api的位置有誤,res.ok會得到false,最後進入catch階段.
  .then((res) => {
    if (res.ok) {
      return res.json();
    } else {
      console.log("error");
    }
  })
  .then((data) => {
    console.log(data);
  })
  .catch((err) => console.error(err));
  • res.json(),是將得到的物件進一步轉換為可使用的資料,此外還有其他方法:arrayBuffer()、blob()、formData()、json()、text().
處理fetch之後res的方法 說明
text() 得到文本字串
json() 得到json对象
formData() 得到formData表單對象
blob() 得到二進制blob對象(可處理圖片檔案)
arrayBuffer() 得到二進制arrayBuffer對象
  • fetch本身可以選擇性的帶入一個參數物件,如下:
fetch(api, {
  body: JSON.stringify(data),
  cache: "no-cache",
  credentials: "same-origin",
  headers: {
    "user-agent": "Mozilla/4.0 MDN Example",
    "content-type": "application/json",
  },
  method: "POST",
  mode: "cors",
}).then((res) => res.json())
  .then((data) => {
    console.log(data);
  })
參數 介紹
body http請求參數
cache 是否快取,有no-cache, reload, force-cache, only-if-cached
credentials cookie設置,有三種include、same-origin、omit.默認為omit不帶cookie;same-origin 同源請求會帶cookie;include無論跨域或者同源都會夾帶cookie.
headers http請求的表頭設置
method 請求方法,有GET, POST, PUT, DELETE等等,默認為GET.
mode 指定請求模式,有no-cors, cors, same-origin.默認為同源same-origin

2. 樣板字面值

  • 允許嵌入運算式的字串字面值(string literals).將內容包覆在反引號``之中.並且可以在${}錢字號大括弧中,放入你要執行的運算.
const test = `This year is ${new Date().getFullYear()}`;
// This year is 2024

const name = "Jack";
const math = 95;
const english = 100;
console.log(`${name} gets ${math + english} grades`);
// Jack gets 195 grades
  • 利用樣板字面值生產出大量的dom,並且將它渲染在畫面上.
<ul class="students"></ul>

const students = document.querySelector(".students");
// 取dom元素

const list = ["Jack", "Ella", "Mason", "Sherry", "Thompson","verna"];
// 清單陣列

let template = "";
// 要渲染在畫面用的字串結構

list.forEach((name, index) => {
  template += `<li>${index + 1}. ${name}</li>`;
})
// 跑迴圈將list清單資料一一變成<li>包覆的字串,結合在template中

students.innerHTML = template;
// 渲染在畫面中

心得

在用vue框架之後,v-for實在太方便,不太需要自己手動渲染出大量的dom結構.fetch部分也沒用到,因為都用axios去操作資料庫.

框架真的節省了不少時間,無腦v-for的菜逼八><


上一篇
Flex Pannels Image Gallery 伸縮自如的畫廊
下一篇
Array Cardio陣列方法
系列文
鱷魚帶我練習JavaScript之個人練功坊17
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言