1.  버스 노선 가져오기

html 코드
<body>
<table>
    <thead>
        <tr>
            <th>버스번호</th>
            <th>버스등급</th>
            <th>평일요금</th>
            <th>평일 시간표</th>
            <th>주말 시간표</th>
        </tr>
    </thead>
    <tbody>

    </tbody>
</table>
<div>
    <input type="button" value="대구">
    <input type="button" value="구미">
    <input type="button" value="경산">
    <input type="button" value="포항">
</div>
</body>

 

css 코드
table, td, th {
    border-collapse: collapse;
    border: 2px solid black;
}

table th {
    height: 50px;
}

table td {
    padding: 15px;
}


table th:first-child {
    width: 200px;
}

table th:nth-child(2) {
    width: 100px;
}

table th:nth-child(3) {
    width: 200px;
}

table th:nth-child(4) {
    width: 550px;
}

table th:last-child {
    width: 550px;
}

div {
    margin: 0 auto;
    padding: 20px;
    text-align: center;
    width: 1000px;
}
div input {
    width: 70px;
    height: 40px;
    background-color: #3a4bb9;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    padding: 5px 10px;
}
div input:hover {
    background-color: white;
    color: #3a4bb9;
}

자바스크립트 코드
document.addEventListener('DOMContentLoaded', function () {

    const btns = document.querySelectorAll('[type=button]');

    btns.forEach(function (item) {
        item.addEventListener('click', function () {
            const cityName = item.getAttribute('value'); // value 값 변수에 담기
            let url = getUrl() // 함수값을 변수에 담기
            printlist(url, cityName); // 함수 호출
        });
    });

    // 1, 2 터미널 각각 분류된 평일 및 주말 시간표를 합치는 함수 만들기
    const sortStr = function (string1, string2) { 
        // 기본 데이터는 문자열. 2개의 문자열을 결합하고, ',' 기준으로 배열로 변환
        let tempList = (string1 + ', ' + string2).split(",");
        tempList = [...new Set(tempList)]; // set으로 중복값 제거
        tempList = tempList.map((item) => item.trim()) // 공백제거
        tempList.sort(); // 오름차순 정렬

        // 현재 시간 구해서 지나간 시간이면 연하게 출력.
        const today = new Date();
        const todayTime = `${today.getHours()}${today.getMinutes()}`;
        // console.log(todayTime)
        tempList = tempList.map((item) => {
            console.log(Number(item))
            return Number(item) < Number(todayTime) ? `<span style="color: #cccccc">${item}</span>` : item;
        });

        return tempList.join(", "); // 배열을 문자열로 변환
    }

    const getUrl = function () {
        const service_key = 'uAhO32pV0qa7BDOmkJLhw2ZyOB9i5bGj7cMN8cuuHmKIwyyf29lHLjym8hBXdIaXyvAI1IyLvQZopk5HW233qQ=='
        const para = `?serviceKey=${service_key}&area=6&numOfRows=100&pageNo=1&type=json`
        return 'http://apis.data.go.kr/B551177/BusInformation/getBusInfo' + para
        // console.log(url)
    }

    const printlist = function (getUrl, cityName) {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', getUrl);
        xhr.onreadystatechange = () => {
            
            if (xhr.readyState !== XMLHttpRequest.DONE) return;

            if (xhr.status === 200) {
                console.log(xhr.response);
                jsonData = JSON.parse(xhr.response);
                //console.log(jsonData);

                const routes = jsonData.response.body.items;
                //console.log(routes)
                const tBody = document.querySelector("tbody");

                while (tBody.firstChild) {
                    tBody.removeChild(tBody.firstChild);
                }

                for (route of routes) {
                    //console.log(route["routeinfo"])

                    if (route["routeinfo"].indexOf(cityName) !== -1) {
                        const trTag = document.createElement('tr');
                        console.log(route)

                        trTag.innerHTML = `
                            <td>${route["busnumber"]}</td>
                            <td>${route["busclass"]}</td>
                            <td>${route["adultfare"]}</td>
                            <td>${sortStr(route["t1wdayt"], route["t2wdayt"])}</td>
                            <td>${sortStr(route["t1wt"], route["t2wt"])}</td>`

                        tBody.appendChild(trTag);
                    }
                }

            } else {
                console.error('Error', xhr.status, xhr.statusText);
            }
        }
        xhr.send();
    }
});

 


2.  항공 출도착 정보 

html 코드
<body>
<table>
    <div>
        <input type="button" id="NRT" value="나리타">
        <input type="button" id="CTS" value="삿포로">
        <input type="button" id="KIX" value="오사카/간사이">
        <input type="button" id="FUK" value="후쿠오카">
        <input type="button" id="HKG" value="홍콩">
    </div>

    <thead>
    <tr>
        <th>항공사</th>
        <th>편명</th>
        <th>예정시간</th>
        <th>도착지 공항</th>
    </tr>
    </thead>
    <tbody>

    </tbody>
</table>
</body>

 

css 코드
table {
    margin: 20px auto;
}

table, td, th {
    border-collapse: collapse;
    border: 2px solid black;
}

table th {
    height: 50px;
}

table td {
    padding: 15px;
    text-align: center;
}


table th:first-child {
    width: 200px;
}
table th:nth-child(2) {
    width: 60px;
}
table th:nth-child(3) {
    width: 150px;
}
table th:nth-child(4) {
    width: 160px;
}

div {
    margin: 0 auto;
    padding: 20px;
    text-align: center;
    width: 1000px;
}
div input {
    width: 100px;
    height: 40px;
    background-color: #3a4bb9;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    padding: 5px 10px;
}
div input:hover {
    background-color: white;
    color: #3a4bb9;
}

자바스크립트 코드
document.addEventListener('DOMContentLoaded', function () {
    const btns = document.querySelectorAll('[type=button]');

    btns.forEach(function (item) {
        item.addEventListener('click', function () {
            const airport = item.getAttribute("id");
            let url = getUrl(airport)
            printList(url);
        });
    });

    const getUrl = function (airportCode) {
        const service_key = 'uAhO32pV0qa7BDOmkJLhw2ZyOB9i5bGj7cMN8cuuHmKIwyyf29lHLjym8hBXdIaXyvAI1IyLvQZopk5HW233qQ=='
        const para = `?type=json&ServiceKey=${service_key}&airport_code=${airportCode}`
        return 'http://apis.data.go.kr/B551177/StatusOfPassengerFlightsDSOdp/getPassengerDeparturesDSOdp' + para
    }
    //console.log(getUrl())

    const printList = function (getUrl) {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', getUrl);
        xhr.onreadystatechange = () => {
            // readyState 프로퍼티의 값이 DONE : 요청한 데이터의 처리가 완료되어 응답할 준비가 완료됨.
            if (xhr.readyState !== XMLHttpRequest.DONE) return;

            if (xhr.status === 200) { // 서버(url)에 문서가 존재함
                //console.log(xhr.response);
                const jsonData = JSON.parse(xhr.response);
                //console.log(jsonData);

                const airlines = jsonData.response.body.items;
                //console.log(airlines)

                const tBody = document.querySelector("tbody");

                while (tBody.firstChild) {
                    tBody.removeChild(tBody.firstChild);
                }

                for (airline of airlines) {

                    const list = document.createElement('tr');

                    list.innerHTML = `
                    <td>${airline['airline']}</td>
                    <td>${airline['flightId']}</td>
                    <td>${airline['estimatedDateTime']}</td>
                    <td>${airline['airport']}</td>`

                    tBody.appendChild(list);
                }

            } else {
                console.error('Error', xhr.status, xhr.statusText);
            }
        }
        xhr.send();
    }
});

 

 

 

 

[ 내용 참고 : IT 학원 강의 ]

+ Recent posts