본문 바로가기
[스파르타 코딩클럽]/비개발자를 위한, 웹개발 종합반

Fetch연습2

by 수민띠 2023. 2. 20.

fetch연습2

따릉이 OpenAPI : http://spartacodingclub.shop/sparta_api/seoulbike

필요 데이터 확인 : stationName: 정류소이름, parkingBikeTotCnt : 주차 현황, rackTotCnt : 총 주차공간

 

// 페이지 로딩 시 중괄호 안의 내용 즉시 실행
$(document).ready(function(){
})

 

step1. 따릉이 OpenAPI를 fetch한다.

fetch("http://spartacodingclub.shop/sparta_api/seoulbike")
.then(res => res.json())
.then(data => {})

 

step2. 리스트([])인 부분을 추려 변수에 저장

fetch("http://spartacodingclub.shop/sparta_api/seoulbike")
.then(res => res.json())
.then(data => {
  let rows = data['getStationList']['row']
})

 

step3. list를 돌며 필요한 정보 저장 (forEach)

fetch("http://spartacodingclub.shop/sparta_api/seoulbike")
.then(res => res.json())
.then(data => {
   let rows = data['getStationList']['row']
   rows.forEach((a) => {
     let name = a['stationName']
     let rack = a['rackTotCnt']
     let bike = a['parkingBikeTotCnt']
   })
})

 

step4 진행 전에 추가할 요소가 들어가야되는 id값과 추가할 요소 뼈대 찾기

step4. 요소 추가하기 

fetch("http://spartacodingclub.shop/sparta_api/seoulbike")
.then(res => res.json())
.then(data => {
	let rows = data['getStationList']['row']
    rows.forEach((a) => {
    	let name = a['stationName']
        let rack = a['rackTotCnt']
        let bike = a['parkingBikeTotCnt']
        
        let temp_html = `<tr>
                           <td>${name}</td>
                           <td>${rack}</td>
                           <td>${bike}</td>
                        </tr>`
        $('#names-q1').append(html_html)
    })
})

 

step5. 조건 걸기

//<style> .red{color:red;} </style>
...
fetch("http://spartacodingclub.shop/sparta_api/seoulbike")
.then(res => res.json())
.then(data => {
	let rows = data['getStationList']['row']
    rows.forEach((a) => {
    	let name = a['stationName']
        let rack = a['rackTotCnt']
        let bike = a['parkingBikeTotCnt']
        
        let temp_html = ``
        if(bike < 5){
            temp_html = `<tr class="red">
                              <td>${name}</td>
                              <td>${rack}</td>
                              <td>${bike}</td>
                         </tr>`
        }else{
            temp_html = `<tr>
                              <td>${name}</td>
                              <td>${rack}</td>
                              <td>${bike}</td>
                         </tr>`
        }
        $('#names-q1').append(html_html)
    })
})