투케이2K

62. (Http/Ajax) post body json : http 요청 및 reponse 데이터 JSON.parse 사용해 model 객체에 매핑 수행 본문

Http & Api

62. (Http/Ajax) post body json : http 요청 및 reponse 데이터 JSON.parse 사용해 model 객체에 매핑 수행

투케이2K 2023. 12. 29. 11:34
반응형

[개발 환경 설정]

개발 툴 : Edit++

개발 기술 : Ajax

 

[소스 코드]

    <!-- ===================================================================================================== -->
    <!-- [CDN 주소 설정] -->
    <!-- ===================================================================================================== -->
    <script src="https://code.jquery.com/jquery-latest.min.js"></script>
    <!-- ===================================================================================================== -->






    <!-- ===================================================================================================== -->
    <!-- [자바스크립트 코드 지정] -->
    <!-- ===================================================================================================== -->
    <script>


        /*
        -----------------------------------------
        [요약 설명]
        -----------------------------------------
        1. JSON.stringify : Object 를 json 형식 문자열로 변환해줍니다
        -----------------------------------------
        2. JSON.parse : Json String 문자열을 Object 로 변환해줍니다
        -----------------------------------------
        */



        // [전역 변수 선언 json 파싱 객체]
        var userInfo = {
            "userId" : "",
            "id" : 0
        };



        // [html 최초 로드 및 이벤트 상시 대기 실시] 
        window.onload = function() {
            console.log("");
            console.log("=========================================");
            console.log("[window onload] : [start]");
            console.log("=========================================");
            console.log(""); 


            // [로직 처리 실시]
            try {

                // [Body에 첨부할 json 데이터]
                var jsonData = { "userId" : 1, "id" : 1 };  


                // [ajax call]
                $.ajax({

                    // [요청 시작 부분]               
                    url: "https://jsonplaceholder.typicode.com/posts", // 요청 주소
                    data: JSON.stringify(jsonData), // 요청 데이터

                    type: "POST", // 전송 타입

                    async: true, // 비동기 여부

                    timeout: 10000, // 타임 아웃 설정

                    dataType: 'JSON', // 데이터 타입 : response

                    cache : false, // 캐시 사용 여부   

                    contentType: "application/json; charset=utf-8", // 헤더의 Content-Type을 설정
                                    
                    // [응답 확인 부분]
                    success: function(response) {
                           
                        // [JSON 데이터 파싱 >> userInfo 매핑 수행]
                        userInfo = JSON.parse(JSON.stringify(response));


                        // [로그 출력]
                        console.log("");
                        console.log("=========================================");
                        console.log("[response] : [success]]");
                        console.log("-----------------------------------------");
                        console.log("[response] : " + JSON.stringify(response));
                        console.log("-----------------------------------------");
                        console.log("[userId] : " + userInfo.userId);
                        console.log("-----------------------------------------");
                        console.log("[id] : " + userInfo.id);
                        console.log("=========================================");
                        console.log("");

                    },
                                    
                    // [에러 확인 부분]
                    error: function(xhr) {
                        console.log("");
                        console.log("=========================================");
                        console.log("[response] : [error]]");
                        console.log("-----------------------------------------");
                        console.log("[error] : " + JSON.stringify(xhr));
                        console.log("=========================================");
                        console.log("");   


                    },
                                    
                    // [완료 확인 부분]
                    complete:function(data, textStatus) {     
                    }
                });

            }
            catch (err){
                console.error("");
                console.error("=========================================");
                console.error("[window onload] : [catch] : Error");
                console.error("----------------------------------------");
                console.error("[err] :: " + err);
                console.error("=========================================");
                console.error(""); 
            }

        }; 

        
    </script>
 

[결과 출력]

 

=========================================
[response] : [success]]
-----------------------------------------
[response] : {"userId":1,"id":101}
-----------------------------------------
[userId] : 1
-----------------------------------------
[id] : 101
=========================================

 

반응형
Comments