[ JS / AJAX ] 비동기 통신을 간단히 구현해보자

2024. 6. 2. 11:36· FRONT-END/└ JS

환경 : Visual Studio Code / Spring Tool Suite 4

 

 

 

1. (스프링) 프로젝트 생성 후 java 파일을 생성 하여 아래 코드 작성 - 백그라운드 코딩

   - AjaxRestController.java

package com.kh.spring11.restcontroller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//@Controller //사용자에게 화면을 전송하는 컨트롤러

@CrossOrigin //외부에서의 비동기 통신을 허용하는 설정
@RestController //사용자에게 데이터를 전송하는 컨트롤러(화면x)
public class AjaxRestController {
	
	@RequestMapping("/hello")
	public String hello() {
		return "Hello Ajax!";
	}
}

 

 

2. (html) 통신할 주소를 설정하여 코드 작성

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Javascript 예제</title>

    <!-- 구글 폰트 -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@100..900&display=swap" rel="stylesheet">
     
    <!-- 내가 구현할 스타일 -->
    <link rel="stylesheet" type="text/css" href="../css/commons.css">
    <link rel="stylesheet" type="text/css" href="../css/test.css">
    
    <!-- font awesome 아이콘 CDN -->
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    
    <style>

    </style>

    <!-- jquery cdn -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
    <!-- 내가 만든 스크립트 추가(jQuery를 사용했으니 jQuery CDN 아래 작성) -->
    <script src="commons.js"></script>
    <!-- javascript를 의도적으로 head 자리에 배치해서 가장 먼저 실행되도록 구현 -->
    <script type="text/javascript">
        $(function(){
            $(".btn-load").click(function(){
                //목표 : 스프링에서 만들어둔 페이지를 비동기로 불러오는 것
                $.ajax({
                    //key:value //객체를 넣어야 됨
                    url : "http://localhost:8080/hello", //나 여기랑 통신할래
                    success : function(response) {
                        console.log(response);
                    }
                }); 
            });
        });
    </script>
</head>
<body>

    <div class="container w-500">
        <div class="cell center">
            <h1>비동기 통신(AJAX)</h1>
        </div>
        <div class="cell">
            <button class="btn positive w-100 btn-load">불러오기</button>
        </div>
    </div>

</body>
</html>

 

 

3. 실행결과 확인 :  스프링의 해당 프로젝트를 실행해둔 상태에서 html 파일 실행 

 

     - 성공 화면

성공사례

    - 실패 화면

실패 사례 (스프링이 꺼져있는 경우)

 

 

 

개인 공부 기록용입니다:)

728x90