본문 바로가기
jQuery

[jQuery / ajax] 서버로 데이터 전송 시 특수문자 깨지는 경우

by 네모세모동동 2024. 7. 6.

 

특수문자가 포함된 데이터를 넘기는 경우, 특수문자가 변환되어 넘어가는 경우를 볼 수 있다.

 

function save() {
	$.ajax({
		url : '/user/saveUser',
		type : 'post',
		data: $('#saveForm').serializeObject(),
		async : false,
		success : function ( result) {
			if( result.result != undefined && result.result != null && result.result == 'success') {
				alert( "저장되었습니다.");
 			} else {
				alert("처리중 오류가 발생했습니다.")
			}
		},
		error:function( jqXHR, textStatus, errorThrown ){
		}
	});
}

 

예시로 저장할 form을 serializeObject로만 <특수문자="테스트!!"> 를 전송한다고 할 때

전송 전 콘솔창에서는 아래와 같이 출력되지만

 

서버 콘솔창에 출력해보면 변환되어 있는 것을 볼 수 있다.

 

 

여기서 JSON.stringify를 사용하여 serializeObject를 한번 더 감싸주면 Object가 문자열로 바뀐 것을 확인할 수 있다.

 

 

이를 서버로 넘겨보면 

 

특수문자가 깨지지 않고 잘 전송되는 것을 확인할 수 있다!!😉

 

📍 JSON.stringify를 쓰는 경우에는 두가지를 꼭❗ 확인해줘야한다.
         1.  contentType : "application/json”   ( "application/json; charset=UTF-8” )
         2. @RequestBody

 

 

ajax 부분에 contentType으로 'application/json; charset=UTF-8'을 명시해줘야하며

JSON.stringify는 JAVA단에서   @RequestBody 로 데이터를 받아줘야한다!

 

 

위 코드를 수정한 코드이다.

function save() {
	$.ajax({
		url : '/user/saveUser',
		type : 'post',
		contentType : "application/json; charset=UTF-8",
		data: JSON.stringify($('#saveForm').serializeObject()),
		async : false,
		success : function ( result) {
			if( result.result != undefined && result.result != null && result.result == 'success') {
				alert( "저장되었습니다.");
 			} else {
				alert("처리중 오류가 발생했습니다.")
			}
		},
		error:function( jqXHR, textStatus, errorThrown ){
		}
	});
}

 

@RequestMapping(value="/user/saveUser")
public ModelAndView saveUser(@RequestBody Map<String, Object> param) throws Exception {
	System.out.println("param : " + param);
    
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("result", "success");
    
    return new ModelAndView(jsonView, map);
}