본문 바로가기

Backend/AJAX

Ajax (Asynchronous JavaScript and XML)

Ajax (Asynchronous JavaScript and XML)

  • 클라이언트에서 비동기 방식으로 자바스크립트를 이용하여
  • 화면 전환 없이 서버 측에 데이터를 요청하고 응답 받을 때 사용
  • HTML, XML, JSON, 텍스트 등의 데이터 처리 가능
  • 웹서버 환경에서 실행

Ajax 주요 메소드

  • $.ajax()
    • 데이터를 서버에 HTTP POST, GET 방식으로 전송 가능
    • HTML, XML, JSON, 텍스트 유형의 데이터를 요청할 수 있는 통합적인 메소드
    • $.get(), $.post(), $.getJSON() 메소드의 기능을 하나로 합쳐 놓은 기능
    • 지정한 url 경로에 있는 파일(url 매핑 이름)의 데이터 전송 & 입력한 url 경로의 파일(url 매핑 이름)로부터 요청한 데이터를 불러옴
  • serialize()
    • 폼에 입력된 값을 쿼리 스트링 방식의 데이터로 변환하여 액션 페이지에 전송
    • ex) ‘id=abcd&pass=1234…’

$.ajax() 메소드의 기본 형식

$.ajax({
  url:"전송되는 요청 url 매핑 이름",
  type:"데이터 전송 방식 (get/post)",
  data:"전송할 데이터",
  dataType:"요청하는 데이터의 타입 (html/xml/json),
  success:function(result) {   
    // 서버로부터 응답(return 값)을 result로 받음
    전송 및 요청 성공 시 실행 부분
  },
  error:function(){
    오류 발생 시 실행 부분
  },
  complete:function(){
    전송 및 요청 완료 시 실행 부분
  }
});

servlet-context.xml : 추가 - js resources 경로 매핑 지정

<!-- 내부 리소스 -->
<resources location="/resources/image/" mapping="image/**" />
<resources location="/resources/js/" mapping="js/**" />

 

Ajax 예제 1 : 로그인 성공 / 실패 여부 결과 받아서 alert()로 출력 (프로젝트명 : spring_mvc_mybatis)

AjaxController

package com.spring_mvc.mybatis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spring_mvc.mybatis.service.ProductService;

@Controller
public class AjaxController {
	
	// DI 설정
	@Autowired
	ProductService service;
	
	// 로그인 폼으로 이동
	@RequestMapping("/loginForm")
	public String loginForm() {
		return "ajax/loginForm"; //loginForm.jsp 뷰 페이지
	}
	
	// 로그인 처리
	@ResponseBody
	@RequestMapping("/login")
//	public String loginCheck(@RequestParam("user_id") String id,
//										   @RequestParam("user_pw") String pw) {
	public String loginCheck(@RequestParam("id") String id,
			   							   @RequestParam("pw") String pw) {
		// 로그인 체크 (가정)
		String result = "";
		if(id.equals("abcd") && pw.equals("1234"))
			result ="success";
		else
			result = "fail";
		
		return result; //
		
		//@ResponseBody가 없는 경우 : success.jsp 또는 fail.jsp 반환
		//@ResponseBody가 있는 경우 : 본문(body)에 result 포함해서 반환 (새 페이지에서 sucess 또는 fail 출력)
	}
}

 

index.jsp : Ajax 메뉴 추가

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>index 페이지</title>
	</head>
	<body>
			<h3>MyBatis 사용 DB 연동</h3>
			<h4>상품 관리 시스템</h4>
			<br>
			<a href="product/listAllProduct">전체 상품 조회</a><br><br>
			<a href="product/newProductForm">상품 등록</a><br><br>
			<a href="product/productSearchForm">상품 검색</a><br><br>
			<a href="product/productSearchForm2">상품 검색2</a><br><br>
			<img src="/mybatis/resources/image/apple.png">
			
			<br><br>
			<hr>
			<h3>Ajax 연습</h3>
			<a href="loginForm">로그인</a><br><br>
	</body>
</html>

 

loginForm.jsp 생성

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>로그인폼</title>
		<script src="js/jquery-3.6.0.min.js"></script>
		<script src="js/login.js"></script>
	</head>
	<body>
		  <!-- <form id="frmLogin" method="post" action="login" > -->
		  <form id="frmLogin"> <!-- Ajax 사용하는 경우  -->
			   아이디  :<input type="text" id="user_id" name="user_id"><br>
		     비밀번호:<input type="password" id="user_pw" name="user_pw" ><br>
		    <input type="submit" value="로그인">  <input type="reset" value="다시입력">
		  </form>
	</body>
</html>

 

login.js

/**
 * login.js
 */
 
 $(document).ready(function(){
	$('#frmLogin').on('submit', function(){
		event.preventDefault();
		
		var userId = $('#user_id').val();
		var userPw = $('#user_pw').val();
		
		$.ajax({
			type:"post",
			url:"login",
			data:{"id": userId,
					  "pw": userPw},  /* 컨트롤러에서 받을 때 : id, pw로 받음*/
			dataType:'text',
			success:function(result){
				//alert(result);
				if(result == "success")
					message = "로그인 성공";
				else
				   message = "로그인 실패";
				   
				alert(message);
			},
			error:function(data, textStatus){
				alert("전송 실패");
			},
			complete:function(data, textStatus){
				alert("작업을 완료했습니다");
			}
		});
	});	
});

Ajax 예제 2 : 로그인 성공 후 다른 페이지로 포워딩

loginForm2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>로그인폼</title>
		<script src="js/jquery-3.6.0.min.js"></script>
		<script src="js/login2.js"></script>
	</head>
	<body>
		  <!-- <form id="frmLogin" method="post" action="login" > -->
		  <form id="frmLogin2"> <!-- Ajax 사용하는 경우  -->
			   아이디  :<input type="text" id="user_id" name="user_id"><br>
		     비밀번호:<input type="password" id="user_pw" name="user_pw" ><br>
		    <input type="submit" value="로그인">  <input type="reset" value="다시입력">
		  </form>
	</body>
</html>

 

login2.js

/**
 * login2.js
 */
 
 $(document).ready(function(){
	$('#frmLogin2').on('submit', function(){
		event.preventDefault();
		
		var userId = $('#user_id').val();
		var userPw = $('#user_pw').val();
		
		$.ajax({
			type:"post",
			url:"login",
			data:{"id": userId,
					  "pw": userPw},  /* 컨트롤러에서 받을 때 : id, pw로 받음*/
			dataType:'text',
			success:function(result){
				// alert(result);
				if(result=="success"){
					alert("로그인 성공\n상품 조회 회면으로 이동합니다.");
					location.href="/mybatis/product/listAllProduct";
				} else {
					alert("로그인 실패");
				}	
			},
			error:function(data, textStatus){
				alert("전송 실패");
			},
			complete:function(data, textStatus){
				alert("작업을 완료했습니다");
			}
		});
	});	
});

 

AjaxController

package com.spring_mvc.mybatis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spring_mvc.mybatis.service.ProductService;

@Controller
public class AjaxController {
	
	// DI 설정
	@Autowired
	ProductService service;
	
	// 로그인 폼으로 이동
	@RequestMapping("/loginForm")
	public String loginForm() {
		return "ajax/loginForm"; //loginForm.jsp 뷰 페이지
	}
	
	// 로그인 처리
	@ResponseBody
	@RequestMapping("/login")
//	public String loginCheck(@RequestParam("user_id") String id,
//										   @RequestParam("user_pw") String pw) {
	public String loginCheck(@RequestParam("id") String id,
			   							   @RequestParam("pw") String pw) {
		// 로그인 체크 (가정)
		String result = "";
		if(id.equals("abcd") && pw.equals("1234"))
			result ="success";
		else
			result = "fail";
		
		return result; //
		
		//@ResponseBody가 없는 경우 : success.jsp 또는 fail.jsp 반환
		//@ResponseBody가 있는 경우 : 본문(body)에 result 포함해서 반환 (새 페이지에서 sucess 또는 fail 출력)
	}
	
	// 로그인 폼2로 이동
	@RequestMapping("/loginForm2")
	public String loginForm2() {
		return "ajax/loginForm2"; //loginForm.jsp 뷰 페이지
	}
}

 

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>index 페이지</title>
	</head>
	<body>
			<h3>MyBatis 사용 DB 연동</h3>
			<h4>상품 관리 시스템</h4>
			<br>
			<a href="product/listAllProduct">전체 상품 조회</a><br><br>
			<a href="product/newProductForm">상품 등록</a><br><br>
			<a href="product/productSearchForm">상품 검색</a><br><br>
			<a href="product/productSearchForm2">상품 검색2</a><br><br>
			<img src="/mybatis/resources/image/apple.png">
			
			<br><br>
			<hr>
			<h3>Ajax 연습</h3>
			<a href="loginForm">로그인</a><br><br>
			<a href="loginForm2">로그인2</a><br><br>
	</body>
</html>

 

'Backend > AJAX' 카테고리의 다른 글

ajax 기초 개념 및 사용법  (0) 2022.03.02
@RestController 이용한 REST 기능 구현  (0) 2022.01.12
Synchronous(동기식) / Asynchronous(비동기식) 통신  (0) 2022.01.11
REST  (0) 2022.01.11