AJAX

Grace Goh·2023년 4월 27일
0

AJAX

목록 보기
1/1

Asynchronous Javascript And XML
비동기* JavaScript XML

* 동시에 일어나지 않는다.

페이지 전체를 로드하지 않고 비동기적으로 데이터를 가져와서
부분적으로 사이트를 변경하는 기술.







GET 요청 보내는 방법

  1. 주소창에 주소를 입력하여 GET 요청 -> 웹툰 나옴.

  2. 버튼으로 GET 요청

    <form action="comic.naver.com" type="get">
        <button type="submit"> // 누르면 get 요청됨... 새로고침
    
    </form>
  3. AJAX로 GET 요청
    새로고침 없이도 서버에 GET 요청하는 JavaScript 코드




AJAX로 GET 요청하기

  1. 기존 JS 방식
<script>

    var ajax = new XMLHttpRequest();
        ajax.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                console.log(ajax.responseText)
            }
        };

        ajax.open("GET", "https://codingapple1.github.io/price.json", true);
        ajax.send();
        
</script>

  1. 최신 JS 방식
<script>

    fetch('https://codingapple1.github.io/price.json')
        .then((response) => {
            return response.json()
        })
        .then((결과) => {
            console.log(결과)
        })

</script>

기본 함수 fetch()에 url을 적으면 자동으로 GET 요청을 보내준다.
갖고 온 데이터를 출력하려면 .then() 함수를 붙이고, 함수 내에 다음 콜백 함수를 입력한다.

// 콜백 함수

(response) => {
  	return response.json() // parameter
}

콜백 함수 내의 parameter가 수신한 데이터다.
파싱한 결과를 출력하고 싶으면 다시 .then()을 붙여준다.
복붙해서 쓰는 문법이기 때문에 자세한 원리를 알 필요는 없다.



에러 처리

를 하고 싶다면 뒤에 .catch()를 붙여준다.
정확히 에러를 캐치하고 싶다면 if문을 삽입한다.

<script>

    fetch('https://codingapple1.github.io/price.json')
        .then((response) => {
  			if (!response.ok) {
                throw new Error ('400 or 500 Error');
            }
            return response.json()
        })
        .then((결과) => {
            console.log(결과)
        })
		.catch(() => {
  			console.log('Error')
		}

</script>

.then() 함수를 붙이지 않는 방법

<script>

    async function function_to_get_data() {
        var response = await fetch('https://codingapple1.github.io/price.json');
        if (!response.ok) {
            throw new Error ('400 or 500 Error');
        }
        var result = await response.json();
        console.log(result)
    }
    function_to_get_data().catch(() => {
        console.log('Error')
    });

</script>
profile
Español, Inglés, Coreano y Python

0개의 댓글