Spring

[Spring / 비동기 #9] ajax의 문제점_22.07.29 [13일차]

양빵빵 2022. 7. 29. 11:10
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
   
    <script>

 

        // 비동기 get요청 처리 함수
        function get(url) {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', url);
            xhr.send();
           
            xhr.onload = e => {
                // 서버 응답 데이터를 리턴
                console.log('server response: ',xhr.response);
                return JSON.parse(xhr.response);
            };
        }

 

        (function() {

 

            const foundUser = get('http://localhost:5000/user/1');
            const boardList = get('http://localhost:5000/board');

 

            console.log('user:', foundUser);
            console.log('board:', boardList);

 

        })();
    </script>

 

</body>
</html>
 
 
 
 
== 서버 실행후 

 

 

지금 구조상 함수의 리턴값으로 응답 데이터를 받는게 불가능 하다.

- 함수 호출을 브라우저가 하기 때문에

 - onload 에서 데이터를 즉각 소비 해야 된다.

== 아래는 다시 약간 수정한 코드

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <script>

        // 비동기 get요청 처리 함수
        function get(url) {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', url);
            xhr.send();

            function getRespData(e) {
                // 서버 응답 데이터를 리턴
                console.log('server response: ',xhr.response);
                return JSON.parse(xhr.response);
            };
            
            xhr.onload = getRespData;
        }

        (function() {

            const foundUser = get('http://localhost:5000/user/1');
            const boardList = get('http://localhost:5000/board');

            console.log('user:', foundUser);
            console.log('board:', boardList);

        })();
    </script>

</body>
</html>