본문 바로가기

javascript/javascript30

06 - Ajax Type Ahead

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<script>
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));
 
function findMatches(wordToMatch, cities) {
  return cities.filter(place => {
    // here we need to figure out if the city or state matches what was searched
    const regex = new RegExp(wordToMatch, 'gi');
    return place.city.match(regex) || place.state.match(regex)
  });
}
 
function numberWithCommas(x) {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
 
function displayMatches() {
  const matchArray = findMatches(this.value, cities);
  const html = matchArray.map(place => {
    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>`);
    return `
      <li>
        <span class="name">${cityName}, ${stateName}</span>
        <span class="population">${numberWithCommas(place.population)}</span>
      </li>
    `;
  }).join('');
  suggestions.innerHTML = html;
}
 
const searchInput = document.querySelector('.search');
const suggestions = document.querySelector('.suggestions');
 
searchInput.addEventListener('change', displayMatches);
searchInput.addEventListener('keyup', displayMatches);
 
</script>
cs

이번에는 코드가 많고 길어서 복잡해 보이지만

강의를 듣다보면 그렇게 복잡한 코드도 아니다.

여기서 우선 새로보이는 건 fetch 와 정규표현식 정도 인거같다.

나머지는 저번시간에 다뤘던걸 쓰기때문에 기억이 안난다면 뒤로 돌아가서 복습해보자.


findMatches함수로 city,state를 판단하는것이고

나머지 함수는 글씨에 하이라이트 처리나 이벤트실행을 담당한다.


정규표현식은 정말 어려우면서도 쓰기 좋다. 나중에 기회가 된다면 다뤄보자.

Ajax로 데이터를 받아와서 조건에 맞게 사용하는법을 배운거 같아서 이번 겅의도 유익했던거 같다.