[Ajax]

2025. 4. 8. 18:17·Web

ajax8.do

 방식: GET
 JS 코드

fetch('./ajax8.do')

 Controller

@GetMapping("/ajax8.do")
@ResponseBody
public String ajax8() {
    return "hello";
}

 설명
쿼리 파라미터 없이 단순 GET 요청
컨트롤러에서는 파라미터 없이 단순 처리


 ajax9.do

 방식: GET + 쿼리 파라미터
 JS 코드

fetch('./ajax9.do?mid=' + this.mid)

 Controller

@GetMapping("/ajax9.do")
@ResponseBody
public String ajax9(@RequestParam("mid") String mid) {
    return mid;
}

 설명
?mid=xxx 형태의 쿼리 스트링
@RequestParam으로 특정 파라미터 받아 사용


 ajax10.do

 방식: POST + form-urlencoded
 JS 코드

fetch('./ajax10.do', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: 'mid=' + this.userid
})

 Controller

@PostMapping("/ajax10.do")
@ResponseBody
public String ajax10(@RequestParam("mid") String mid) {
    return mid;
}

 설명
폼 전송처럼 보냄 (application/x-www-form-urlencoded)
@RequestParam으로 받아야 함


 ajax11.do

 방식: POST + JSON
 JS 코드

$.ajax({
    url: './ajax11.do',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({ mid: this.userid })
})

 Controller

@PostMapping("/ajax11.do")
@ResponseBody
public String ajax11(@RequestBody Map<String, String> map) {
    return map.get("mid");
}

 설명
JSON 데이터를 전송함
@RequestBody로 JSON 전체를 받아 Map으로 처리


 ajax12.do

 방식: POST + JSON
 JS 코드

$.ajax({
    url: './ajax12.do',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({ mid: this.userid, mpw: this.userpw })
})

 Controller

@PostMapping("/ajax12.do")
@ResponseBody
public String ajax12(@RequestBody MemberDTO dto) {
    return dto.getMid() + " / " + dto.getMpw();
}

 설명
JSON 데이터를 DTO로 바인딩
@RequestBody는 반드시 JSON 형식일 것


 ajax13.do

 방식: PATCH + JSON
 JS 코드

$.ajax({
    url: './ajax13.do',
    type: 'PATCH',
    contentType: 'application/json',
    data: JSON.stringify({ mid: this.userid, mpw: this.userpw })
})

 Controller

@PatchMapping("/ajax13.do")
@ResponseBody
public String ajax13(@RequestBody MemberDTO dto) {
    return dto.getMid() + " / " + dto.getMpw();
}

 설명
PATCH 방식으로 JSON 데이터 전송
@RequestBody로 DTO 바인딩
PUT과 방식은 같음 (차이점은 의미적인 부분)


 ajax14.do

 방식: DELETE + JSON
 JS 코드

$.ajax({
    url: './ajax14.do',
    type: 'DELETE',
    contentType: 'application/json',
    data: JSON.stringify({ mid: this.userid })
})

 Controller

@DeleteMapping("/ajax14.do")
@ResponseBody
public String ajax14(@RequestBody Map<String, String> map) {
    return map.get("mid");
}

 설명
DELETE 방식으로 JSON 전송
@RequestBody와 Map 조합으로 간단히 처리 가능


 ajax15.do

 방식: PUT + JSON
 JS 코드

$.ajax({
    url: './ajax15.do',
    type: 'PUT',
    contentType: 'application/json',
    data: JSON.stringify({ mid: this.userid, mpw: this.userpw })
})

 Controller

@PutMapping("/ajax15.do")
@ResponseBody
public String ajax15(@RequestBody MemberDTO dto) {
    return dto.getMid() + " / " + dto.getMpw();
}

 설명
PUT 방식으로 JSON 데이터 전송
@RequestBody로 DTO 처리


정리 요약표

요청 방식                  JS 방식                                    Content-Type                                        Spring 수신 방식

GET fetch('?key=value') - @RequestParam
POST (form) x-www-form-urlencoded application/x-www-form-urlencoded @RequestParam, @ModelAttribute
POST (JSON) JSON.stringify({}) application/json @RequestBody
PATCH (JSON) JSON.stringify({}) application/json @RequestBody
DELETE (JSON) JSON.stringify({}) application/json @RequestBody
PUT (JSON) JSON.stringify({}) application/json @RequestBody

 

전체코드 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ECMA - Ajax (GET, POST)</title>
</head>
<body>
<button type="button" id="btn">Ajax GET 통신</button>
<button type="button" id="btn2">Ajax POST 통신</button>
</body>
<script type="module">
import {ajax_network} from "./ajax8.js?v=1";
</script>
</html>
=====
//버튼 클릭시 클래스 및 메소드를 호출 
document.querySelector("#btn").addEventListener("click",function(){
	new ajax_network().ajax_get();
	
});

document.querySelector("#btn2").addEventListener("click",function(){
	new ajax_network2().ajax_idck();
	
});

//Ajax GET
export class ajax_network{
	//axio(react,vue) 안쓰고 fetch씀 (신상)
	//fetch : ECMA에서부터 사용을 했으며 XMLHttpRequest => fetch로 변경
	ajax_get(){
		this.mid = "구나영";
		fetch("./ajax9.do?mid="+this.mid)	//ECMA GET ajax
		.then(function(aa){	//Back-end에서 결과값을 받는 함수 
			return aa.text();	//text(), json() => JSON.parse()
		})
		.then(function(bb){	//Front-end에서 return된 결과 함수를 출력하는 함수 
			console.log(bb);
		})
		.catch(function(error){	//예외처리로 오류 발생시 출력되는 역할 
			console.log(error);
		});
	}
	
	
}

//Ajax POST
export class ajax_network2{
	
	ajax_idck(){
		this.userid="koo";
		this.mid = "mid="+this.userid;	//name형태로 Back-end로 POST 전송 
		fetch("./ajax10.do",{
			method : "POST",	//POST 통신방법 
			headers:{"content-type":"application/x-www-form-urlencoded"},	//이거 안쓰면 에러남	//headers를 이용하여 UTF-8 언어셋
			body : this.mid		//body는 POST전송시 무조건 사용  
		}).then(function(aa){	
			return aa.text();	
		})
		.then(function(bb){	 
			console.log(bb);
		})
		.catch(function(error){	
			console.log(error);
		});
		 
		
	}


}










=====
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ECMA - 배열, FormData를 이용한 Ajax 통신방법</title>
</head>
<body>

</body>
<script type="module">
import {ecma_ajax} from "./ajax9.js";
new ecma_ajax().ajax_arr();
</script>
</html>
=====
export class ecma_ajax{
	
	//배열 생성 후 POST
	ajax_arr(){
//		this.arr = ["koo","lee","yoon"];
//		this.arr = {mid:"koo", mname:"구나영"};
		
		fetch("./ajax11.do",{
			method:"POST",
			
			//아래두줄 세트 => @RequestBody로 받기 => JSONArray, JSONObject로 풀기 
//			headers:{"content-type":"application/json"},
//			body:JSON.stringify(this.arr)

			//아래두줄 세트 => @RequestParam 두개로 받거나 @ModelAttribute dto로 받기 
//			headers:{"content-type":"application/x-www-form-urlencoded"},
//			body:"mid=koo&mname=구나영"	
				
			/* 세트 (JSON.stringify)
			headers:{"content-type":"application/json"},
			body:JSON.stringify({
				mid:"koo",
				mname:"구나영"
			})
			*/
			
			//DTO로 받는 법 (new URLSearchParams)
			//URLSearchParams : 배열(키,원시 모두 가능)을 구성하여 Ajax로 데이터를 전송시키는 방식 
			headers:{"content-type":"application/x-www-form-urlencoded"},
			body:new URLSearchParams({
				mid:"koo",
				mname:"구나영"
			})
			
		}).then(function(aa){	
			return aa.text();	
		})
		.then(function(bb){	 
			console.log(bb);
		})
		.catch(function(error){	
			console.log(error);
		});
		
		
		
	}
	
}
=====
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<!-- 
API Key에 관련된 사항을 체크 
PATCH : update (수정)
PUT : insert (입력)
DELETE : delete (삭제)

GET(보안X), POST(보안) : select (검색)
 -->
<meta charset="UTF-8">
<title>Ajax(PATCH) - REST API Server</title>
<script src="./jquery.js"></script>
<script>
$(function() {
    $("#btn").click(function(){
       var $mid = $("#mid").val();
       //코드 변경 배열(X)
       $.ajax({
          url : "./ajax12.do/patch_myinfo",
          cache : false,
          type : "PATCH",
          dataType : "html",
          contentType : "application/json",
          data : JSON.stringify({
             mid : $mid,
             mname : "홍길동",
             mage : "35",
             memail : "hong@nate.com"
          }),
          success: function($data) {
             console.log($data);
          },
          error : function() {
             console.log("통신 오류 발생!");
          }

          
       });
    });
 });
 
	

</script>

</head>
<body>
아이디 : <input type="text" id="mid"><br>
<input type="button" value="JS 클릭" onclick="ajaxs()"><br>
<input type="button" value="JQ 클릭" id="btn">
</body>
<script>
function ajaxs(){
	var mid = document.getElementById("mid");	//하나만 보내는 경우 
	
	var arr = new Array();	//배열을 보내는 경우 
	arr[0] = mid.value;
	arr[1] = "koonayoung";
	arr[2] = "서울시 마포구";
		
	var http, result;
	
	http = new XMLHttpRequest();
	
//	http.open("PATCH","./ajax12.do/"+mid.value, false);	//하나만 보내는 경우 
//	http.open("PATCH","./ajax12.do/"+arr, false);	//배열을 보내는 경우 
//	http.setRequestHeader("content-type","application/x-www-form-urlencoded");	//하나만 보내는 경우,배열을 보내는 경우


	//배열값 및 보안 코드를 적용하여 API로 연결하는 방식 
	//JSON.stringify=> 받을수있는 방법이없음 위방법으로 써야함 
	http.open("PATCH","./ajax12.do/patch_myinfo", false);	//보안코드 (patch_myinfo라는 단어로 )
	//patch_myinfo 보안 뭐어쩌고 ... 암호화시킴 보안에 좋음 
	http.setRequestHeader("content-type","application/json");	//배열을 JSON으로 보내는 경우 

	http.onload = function(){
		console.log(this.response);
	};
	http.onerror = function(){
		console.log("통신오류발생");
	};
//	http.send();		//하나만 보내는 경우,배열을 보내는 경우
	http.send(JSON.stringify(arr));	// JSON.stringify(arr) => send라는 함수를 이용하여 전달  
	
	
}
</script>
</html>
=====
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ECMA Script - PATCH(Ajax)</title>
</head>
<body>
아이디 : <input type="text" id="mid"><br>
<input type="button" value="ES 클릭" id="btn">
</body>
<script type="module">
import {myinfos} from "./ajax11.js?v=1";
</script>
</html>
=====
document.querySelector("#btn").addEventListener("click",function(){
	new myinfos().ajax_data();
});

//var, let(동일한 변수명을 사용못함), const(상수)
export class myinfos{
	ajax_data(){
		//사용자가 입력한 아이디값을 가져오는 코드
		let mid = document.querySelector("#mid").value;
		this.arr = new Array();	//빈배열을 생성
		this.arr[0] = mid;	//배열에 아이디를 적용
		this.arr[1] = "apink@naver.com";	//이메일
		this.arr[2] = "01010041004";		//전화번호
		this.arr[3] = "서울시 종로구";		//주소
		
		fetch("./ajax12.do/patch_myinfo",{
				method : "PATCH",
				headers : {"content-type":"application/json"},
				body : JSON.stringify(this.arr)
		}).then(function(aa){
			return aa.text();	//Back-end 결과값 받음
		}).then(function(bb){	
			console.log(bb);	//결과값 출력
		});

	}
	
}
=====
<%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Delete, PUT - AJAX</title>
<script src="./jquery.js"></script>
</head>
<body>
   <input type="button" value="JS삭제" onclick="ajax_del()">
   <input type="button" value="ES삭제" id="ajax_del">
</body>
<script>
//JS 삭제 
function ajax_del(){
   var formdata = new FormData();
   formdata.append("midx",5);
   formdata.append("midx",9);
   formdata.append("midx",12);
   //console.log(formdata.getAll("midx"));
   var http,result;
   http = new XMLHttpRequest();
   http.open("DELETE","./ajax13/a123456",false);
   http.setRequestHeader("content-type","application/x-www-form-urlencoded");
   http.onload = function() {
      console.log(this.response);
   };
   http.onerror = function() {
      console.log("통신오류");
   };
   http.send(formdata);
}

//ES 삭제
document.querySelector("#ajax_del").addEventListener("click", function() {
	/*방법 1 : FormData() => @RequestBody 
	var formdata = new FormData();
	   formdata.append("midx",5);
	   formdata.append("midx",9);
	   formdata.append("midx",12);
	   */
	   //방법2 : Array() =>  @RequestBody 
	   this.arr = ["5","9","12"];
	   
	   fetch("./ajax13/a123456",{
		   method:"DELETE",
//			body:formdata	//방법1

headers : {"content-type":"application/json"},
body : JSON.stringify(this.arr)	//방법2

	   }).then(function(aa){	
			return aa.text();	
		}) .then(function(bb){	 
			console.log(bb);
		}) .catch(function(error){	
			console.log(error);
		});
});


</script>
</html>



























=====
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax - @PutMapping => DTO로 처리 </title>
<script src="./jquery.js"></script>
</head>
<body>
입력값 : <input type="text" id="pd1"><br>
입력값 : <input type="text" id="pd2"><br>
입력값 : <input type="text" id="pd3"><br>
입력값 : <input type="text" id="pd4"><br>
입력값 : <input type="text" id="pd5"><br>
<input type="button" value="Ajax전송" onclick="ajax_put()">
</body>
<!-- JS -->
<script>
function ajax_put(){
	var a= 1;
	while(a < 6){
		//eval() : 문자형태를 Script화 시켜주는 역할 함수 
		//eval을 이용해 동적으로 변수 생성 
		eval("pd" + a + " = document.getElementById('pd" + a + "').value;");
		//eval("var pd"+a +"="+ document.getElementById("pd"+a).value);	//한글 안됨 
		a++;
	}
	  
    // 키배열 pd1 ~ pd5
    var keyarray = {
          pd1: pd1,
          pd2: pd2,
          pd3: pd3,
          pd4: pd4,
          pd5: pd5
    };
    var json = JSON.stringify(keyarray);
    console.log(json);
    
    var http,result;
    http = new XMLHttpRequest();
    http.open("PUT","./ajax14/a123456",false);
//    http.setRequestHeader("content-type","application/json");
//    http.setRequestHeader("content-type","application/x-www-form-urlencoded");
    http.onload = function() {
       result = this.response;
       console.log(result);
    }
    http.onerror = function() {
       console.log("통신오류!!");
    }
//	http.send(keyarray);
	http.send(json);
	
}
</script>
<!-- ES -->
<script type="module"></script>
</html>
=====

	// ECMA - Ajax (get)
	@GetMapping("/ajax/ajax9.do")
	public String ajax9(@RequestParam(name="mid") String mid, ServletResponse res) {
		try {
			this.logger.info(mid);
			this.pw = res.getWriter();
			this.pw.write("ok");
			
		} catch (Exception e) {

		}

		return null;
	}

	// ECMA - Ajax (post)
	@PostMapping("/ajax/ajax10.do")
	public String ajax10(@RequestParam(name = "mid") String mid, ServletResponse res) {
		try {
			this.logger.info(mid);
			this.pw = res.getWriter();
			this.pw.write("ok");

		} catch (Exception e) {

		}

		return null;
	}

	// ECMA - Ajax (post) : 배열 전송
	@PostMapping("/ajax/ajax11.do")
	public String ajax11(@ModelAttribute api_dto dto, ServletResponse res) {
		try {
			this.logger.info(dto.getMname().toString());
			this.logger.info(dto.getMid().toString());

			this.pw = res.getWriter();
			this.pw.write("ok");

		} catch (Exception e) {

		}

		return null;
	}
	
	//Ajax(PATCH) - API Server
	//@PathVariable : URL에 파라미터 값을 가져오는 어노테이션 {~} 
	//				가상의 파라미터값 {여기}랑 name="여기" 같아야함 딱하나만 사용가능  
	//				JSON.stringify에 대한 정보값을 처리하지 못함 
	@PatchMapping("/ajax/ajax12.do/{data}")
//	public String ajax12(@PathVariable(name="data") String mid, ServletResponse res) {	//하나만 보낼때, 배열로 보낼때 
	public String ajax12(
			@PathVariable(name="data") String data, 
			@RequestBody String myinfo,
			ServletResponse res) {	//JSON으로 보낼때 
		try {
			/*하나만 보낼때, 배열로 보낼때 
			String user[] = mid.split(",");
			this.logger.info(user[1]);
			this.logger.info(user[2]);
			*/
			
			this.pw = res.getWriter();
			if(data.equals("patch_myinfo")) {
				this.logger.info(myinfo);
				this.pw.write("ok");
			}else {
				this.pw.write("error");
			}
			
			
			

		} catch (Exception e) {

		}
		return null;
	}
	
	
	//@RequestPart : MultipartFile 로 받을때 사용
	//@RequestParam : name 또는 파라미터 
	//@ResponseBody + @Mapping : method 선언시 사용 
	//@ResponseBody : 응답에 대한 결과값을 해당 메소드에 바로 출력할 때 사용
	//@RequestBody : 베열값을 처리하는 어노테이션 
	@DeleteMapping("/ajax/ajax13/{key}")
//			@RequestBody String midx
	//formdata => 헤더:urlencoded,send에태워서  @RequestBody로 받
	
	//@RequestParam Map<Object,Object> midx	//방법2 
	//@RequestBody String midx 	//방법1
	   public String ajax13(ServletResponse res, 		//DELETE
	            @PathVariable(name = "key") String key,
	            @RequestBody String midx
	            //@RequestBody String midx 
	               ) {
	         try {
	            this.pw = res.getWriter();
	            if (key.equals("a123456")) {
	               this.logger.info(midx);
	               
	               this.pw.write("delete_ok");
	            } else {
	               this.pw.write("key error");
	            }
	         } catch (Exception e) {
	            this.pw.write("error");
	         }
	         return null;
	      }
	      

	//@RequestBody String data : 정상적으로 값을 받아서 출력 확인 
	@PutMapping("/ajax/ajax14/{key}")		//insert (DTO기본)
	public String ajax14(ServletResponse res, @PathVariable(name = "key") String key,
			@RequestBody String data
			) {
		try {
			this.pw = res.getWriter();
			if (key.equals("a123456")) {
				this.logger.info(data.toString());
//				this.logger.info(jo.getString("pd1"));
				this.pw.write("ok");

			} else {
				this.pw.write("key error");
			}

		} catch (Exception e) {

		}
		return null;
	}
저작자표시 비영리 변경금지 (새창열림)
'Web' 카테고리의 다른 글
  • [Kakao API] 로그인 기초
  • [Spring] PutMapping + GetMapping 을 이용한 Oracle 데이터 입출력
  • [ECMA]
  • log4j.xml 에러 해결
9na0
9na0
응애
  • 9na0
    구나딩
    9na0
  • 전체
    오늘
    어제
    • 분류 전체보기 (211)
      • Web (118)
      • Java (28)
      • 데이터베이스 (14)
      • 세팅 (12)
      • 과제 (3)
      • 쪽지시험 (2)
      • 정보처리기사 (4)
      • 서버 (25)
  • 블로그 메뉴

    • 링크

      • 포폴
      • 구깃
    • 공지사항

    • 인기 글

    • 태그

      net3
      net4
      io_dto
      Oracle
      noticewriteok
      net1
      net5~10
      re2
      file25_t
      re_java10
      exam1_1~10
      file25
      net2
      file24
      java_io1~10
      notice_writer
      datalist
      macbook pro m4
      ab1
      spring-boot
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.3
    9na0
    [Ajax]
    상단으로

    티스토리툴바