-
Ajax QUIZ 02 - 고양이 & 댕댕이 OpenAPI스파르타코딩/스파르타코딩 2주차 2022. 5. 27. 19:09
* 참고 * 이번 OpenAPI는 list 형식으로 되어있다
고양이 url : https://api.thecatapi.com/v1/images/search
댕댕이 url : https://api.thedogapi.com/v1/images/search
* 참고 *
<img id="img_form_url">
위 img 의 src를 변경하는 방법
$("#img_form_url").attr("src", imgurl);
매우 매우 간단한 랜덤 고양이 사진 띄우기 !
스타트~
이미지 url 데이터를 가져와야한다.
이번 API는 앞서 말했듰이 list 형식으로 불러와진다.
API 첫번째 데이터인 [0]에 ['url'] 데이터를 imgurl 변수에 담아준 후
attr("src", imgurl); 을 id = img-cat 에 담아주면 끝~
<script> function q1() { $('#names-q1').empty(); $.ajax({ type: "GET", url: "https://api.thecatapi.com/v1/images/search", data: {}, success: function (response) { let imgurl = response[0]['url']; $('#img-cat').attr("src",imgurl); } }) } </script>
커엽네 누를때 마다 랜덤 고양이 사진을 가져와준다 ( 댕댕이가 좋으면 댕댕이 API를 사용하면 된다 )
완성!
<전체 code>
<!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 q1() { $('#names-q1').empty(); $.ajax({ type: "GET", url: "https://api.thecatapi.com/v1/images/search", data: {}, success: function (response) { let imgurl = response[0]['url']; $('#img-cat').attr("src",imgurl); } }) } </script> </head> <body> <h1>JQuery+Ajax의 조합을 연습하자!</h1> <hr/> <div class="question-box"> <h2>3. 랜덤 고양이 사진 API를 이용하기</h2> <p>예쁜 고양이 사진을 보여주세요</p> <p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p> <button onclick="q1()">고양이를 보자</button> <div> <img id="img-cat" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"/> </div> </div> </body> </html>
'스파르타코딩 > 스파르타코딩 2주차' 카테고리의 다른 글
2.5주차 (2주차 복습) (0) 2022.05.30 Ajax QUIZ 02 - 따릉이 OpenAPI (0) 2022.05.27 Ajax 연습(2) - QUIZ 01 (서울시 OpenAPI) (0) 2022.05.27 Ajax 연습하기(1) - 서울시 미세먼지 API (0) 2022.05.27 JQuery 연습(3) 통합 코드 (0) 2022.05.26