티스토리 뷰

Spring

[스프링]ajax 이용해보기

김판다 2021. 11. 17. 16:19
@GetMapping("non_ajax")
	public String nonAjax() {
		System.out.println("non ajax 실행!");
		return "non_ajax";
	}

ajax를 사용하지 않는다면 

<title>Insert title here</title>
<script type="text/javascript">
	function test(){
		location.href="non_ajax";
	}
</script>
</head>
<body>
	<h1>일</h1>	<h1>일</h1>
	<h1>일</h1>	<h1>일</h1>
	<h1>일</h1>	<h1>일</h1>
	<h1>일</h1>	<h1>일</h1>
	<button type="button" onclick="test()">click</button>

매번 버튼을 클릭할때마다 새 페이지가 떠버린다.

 

ajax를 이용하기 좋을때는 [더보기] 기능이나 좋아요 같이 클릭하면 숫자가 증가하는 기능들이 좋다고 한다.


1.ajax를 이용해보기

컨트롤러

@GetMapping("ajax")
	public String ajax() {
		System.out.println("ajax 실행!");
		return "ajax";
	}

ajax.jsp

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
	function ajaxTest(){
		$.ajax({
			url: "ajax",
			type: "GET",
			success : function(){alert("통신성공")},
			error : function(){alert("통신실패")}
		})
	}
</script>
</head>
<body>
<h1>일</h1>	<h1>일</h1>
	<h1>일</h1>	<h1>일</h1>
	<h1>일</h1>	<h1>일</h1>
	<h1>일</h1>	<h1>일</h1>
	<button type="button" onclick="ajaxTest()">click</button>
</body>

get 타입의 url이 ajax 로 보내지게 된다

그럼 컨트롤러에서 @GetMapping("ajax") 이 실행되고 콘솔에 ajax 실행! 문구를 띄운다

그리고 다시 ajax로 리턴되니 success가 작동하여 그 안에 있는 function(){}가 실행된다.

성공시 alert('통신성공')이 작동하고 

실패시 aler('통신실패)가 작동한다\

 

==>이것으로 ajax를 처음 연결해서 사용해보았다.

 


2.ajax로 숫자 증가시키기

컨트롤러

@GetMapping("ajax")
	public String ajax() {
		System.out.println("ajax 실행!");
		return "ajax";
	}
	
	static int cnt=0;
	@GetMapping("ajax_result")
	@ResponseBody
	public String ajaxResult() {
		return ++cnt+"";//숫자를 문자화함
	}

@ResponseBody는 ajax통신을 사용할때 필수적으로 써야한다.
특정부분에서 데이터를 주고받을때 쓴다.
@ResponseBody 이 없을시 리턴에 jsp경로써줘야하는데 @ResponseBody 이 있다면 데이터만 해당jsp안에 데이터로 돌아간다

 

ajax.jsp

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
	function ajaxTest(){
		$.ajax({
			url: "ajax_result",
			type: "GET",
			success : function(data){
				$("#count").text(data)
				console.log("성공")
				},
			error : function(){alert("통신실패")}
		})
	}
</script>
</head>
<body>
	<button type="button" onclick="ajaxTest()">click</button>
	<label id="count">0</label>
</body>

컨트롤러에서 jsp로 보낸 데이터는 function(data)의 data에 들어가게된다.

id가 count인 라벨안의 text는 버튼이 눌릴때마다 1씩 증가하는 것을 볼 수 있다.

 

 

 

 

 

 

 

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함