[js][ajax] 1.ajax의 기본 구조 & 간단한 활용 예시

2022. 2. 14. 15:54개발의 흔적/웹

<ajax> 서버의 데이터를 요청하는 java script의 라이브러리!

 

<ajax>의 기본 구조

 

$.ajax({
         type: "GET",
         url: "여기에URL을입력",
         data: {},
         success: function(response){
         console.log(response)
         } 
})

<New js 메소드>

 

/*손쉬운 append()느낌! 
매번 ``에 넣어서 하지말고 
태그 내의 문자들을 바꾸는 방법! */


attr('src', image)          // <button class="" id="" src="OOO"> 
                            //                                에서 src = "image"로 변환!
1
text(txt)                   //<li>OOOOOO </li>    에서 <li>txt</li> 로 변환!

 

 

<예시1>

-서울시 미세먼지 openapi를 get해서 각 구의 미세먼지 수치가 나오게 하고, 수치의 대소에 따라 색을 나타나게하라

<!doctype html>
<html lang="ko">

<head>
<meta charset="UTF-8">
<title>jQuery 연습하고 가기!</title>

<!-- jQuery를 import 합니다 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<style type="text/css">
div.question-box {
margin: 10px 0 20px 0;
}
.bad {color: red;}
.notgood {color: sandybrown;}
.soso {color: yellowgreen;}
.good {color: limegreen;}
.great {color: forestgreen;}
</style>

<script>

function update() {
        $('#seoul_dust').empty()             //업데이트 할때마다 기존에 있는거 지워줌
        $.ajax({
            type: "GET",
            url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
            //서울시 미세먼지 open api
            
            data: {},

            success: function (response) {
                let rows = response['RealtimeCityAir']['row']
                for (let i = 0; i < rows.length; i++) {
                    let gu_name = rows[i]["MSRSTE_NM"]      //서울시 OO구
                    let gu_dust = rows[i]["IDEX_MVL"]       //각 구 미세먼지 수치
                  	let col = dust_color(gu_dust)           //수치에 따른 글자 색
                    let temp_html = `<li class=${col}>${gu_name} : ${gu_dust}</li>`                   
                    $('#seoul_dust').append(temp_html)


                }
            }
        })
    }

function dust_color(n) {                         //먼지 수치에 따른 색깔 변화
            if (n > 120) {
            	return "bad"
            } else if (n > 70) {
                return "notgood"
            } else if (n > 60) {
                return "soso"
            } else if (n > 30) {
                return "good"
            } else {
                return "great"
            }
        }
</script>

</head>

<body>
<h1>jQuery+Ajax의 조합을 연습하자!</h1>

<hr />

<div class="question-box">
<h2>1. 서울시 OpenAPI(실시간 미세먼지 상태)를 이용하기</h2>       //url: 
<p>모든 구의 미세먼지를 표기해주세요</p>                          //for문 이용한 function
<p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>   //empty() 사용
<button onclick="update()">업데이트</button>
<ul id="seoul_dust">                                //여기에 function 사용하고 삽입

</ul>
</div>
</body>

</html>

<왼쪽> 코드 url(api)의 구조 파악    /   <오른쪽> html 코드 출력 결과

 

 

<예시2>

-button 누를때마다 나오는 사진이 다르게 하라!

 

<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>JQuery 연습하고 가기!</title>
<!-- JQuery를 import 합니다 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<style type="text/css">
div.question-box {
margin: 10px 0 20px 0;
}
div.question-box > div {
margin-top: 30px;
}

</style>

<script>
function update() {
    $.ajax({
        type: "GET",
        url:"http://spartacodingclub.shop/sparta_api/rtan",
        data: {},
        success: function(response){
            console.log(response)
            let txt = response["msg"]
            let image = response["url"]
            console.log(txt, image)
            $('#img-rtan').attr('src', image)
            $('#text-rtan').text(txt)

        }


    })
}
</script>

</head>
<body>
<h1>JQuery+Ajax의 조합을 연습하자!</h1>

<hr/>

<div class="question-box">
<h2>3. 르탄이 API를 이용하기!</h2>
<p>아래를 르탄이 사진으로 바꿔주세요</p>
<p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
<button onclick="update()">르탄이 나와</button>
<div>
<img id="img-rtan" width="300" src="http://spartacodingclub.shop/static/images/rtans/SpartaIcon11.png"/>
<h1 id="text-rtan">나는 ㅇㅇㅇ하는 르탄이!</h1>
</div>
</div>
</body>
</html>