상세 컨텐츠

본문 제목

api로 받아온 데이터를 ajax로 바꾸기(이미지,텍스트)

자바스크립트

by 개미는내일도뚠뚠 2022. 1. 18. 09:54

본문

 

'르탄이 나와'버튼을 누를때마다 하단의 이미지와 텍스트가 바뀜.

 

html 코드

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

 JS코드

        function q1() {
// 여기에 코드를 입력하세요
            $.ajax({
                url: "http://spartacodingclub.shop/sparta_api/rtan",
                data: {},
                type: "GET",
                success: function (data) {
                    let url = data['url'];
                    let msg = data['msg'];
                    $('#img-rtan').attr('src', url);
                    $('#text-rtan').text(msg);
                }
            })
        }

success의 data(이름 다른거로 바꿔도 됨)인자에 url에서 받아온 정보가 있음. jquery를 이용해서 이미지와 텍스트를 변경하였음. 이미지의 src를 변경하려는 경우에는 $('변경하려는 태그의선택자').attr('src',입력값) 와같이 작성.

텍스트는  $('변경하려는 태그의선택자').text(입력값) 와같이 작성

관련글 더보기