Ajax Type Ahead


Posted by wayne201299 on 2023-09-25

提供一個城市的資料庫,並建立一個input,每輸入一個字元都要撈取資料,並做與城市的資料庫做模糊比對,將結果列出

  1. fetch資料,並將資料暫存在瀏覽器,並透過JSON解析出檔案內容

         const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
         const cities = [];
         fetch(endpoint)
           .then(blob => blob.json())
           .then(data => cities.push(...data));
    
  2. 建立模糊比對方法,使用正則表示式,g代表global,i代表insensitive

         function findMatch(worldToMatch, cities) {
           return cities.filter(place => {
             const regex = new RegExp(worldToMatch, 'gi');
             return place.city.match(regex) || place.state.match(regex);
           });
         }
    
  3. 建立監聽方法,監聽input,在changekeyup時做搜尋

         searchInput.addEventListener('change', displayMatches);
         searchInput.addEventListener('keyup', displayMatches);
    

    change事件只會在離開element後觸發

  4. 將搜尋到的結果渲染上下拉選單中

    function displayMatches() {
     const findArray = findMatch(this.value, cities);
     const html = findArray.map(place => {
         return `
             <li>
                 <span class='name'>${place.city}, ${place.state} </span>
                 <span class='population'>${place.population}</span>
             </li>
             `
             }).join('');
     suggestions.innerHTML = html
    }
    
  5. 將比對到的字元hightlight

     const regex = new RegExp(this.value, 'gi');
     const cityName = place.city.replace(regex, `<span class='hl'>${this.value}</span>`);
     const stateName = place.state.replace(regex, `<span class='hl'>${this.value}</span>`);
    

知識點

  • HTML5提供了fetch方法,可以直接取的API回傳的資料,回傳的資料是Promise,需要用then來接
  • Blob (Binary Large Object) 是一種數據類型,通常用於存储二進制數據,如圖像、音頻和影片文件,或者其他任何二進制數據。它是一種包含任意數據的數據結構,没有特定的文件格式或編碼規則。
  • const regex = new RegExp(this.value, 'gi');,提供模糊比對
  • Array.join()可以將陣列轉換成長字串

#javascript #html







Related Posts

位元運算子

位元運算子

[ JSP ]   EL 和 JSTL

[ JSP ] EL 和 JSTL

第二章:3 驗證趨勢交易策略是否有效

第二章:3 驗證趨勢交易策略是否有效


Comments