DS's『 행복합시다 』

Carpe Programming/javascript

ajax 전송 시 한글 깨짐

nolite 2012. 12. 12. 11:50
반응형

jQuery 에서 serialize 할 때 한글 깨짐 현상 고치기.

ajax 로 폼 안의 컨트롤의 내용을 보내고자 할 때 굉장히 유용한 jQuery의 serialize() 함수에 커다란 결점이 하나 있는데...

http://api.jquery.com/

 

자바스크립트에서 우선
1. problem = escape(encodeURIComponent(problem)); 코드로 변경해주고

2. $.ajax({type: "POST",
        async: false,
        data: "",
        contentType:"application/x-www-form-urlencoded; charset=UTF-8",

        ...

        ...

 

str = escape(encodeURIComponent(document.searchForm.person.value));

 

서버에서 한글로 다시 변환해 줄 때는 이렇게...

@SuppressWarnings("unchecked")
public HashMap<String, String> getRequestMapHelper(HttpServletRequest request)
{
    HashMap<String, String> map = new HashMap<String, String>();

    Enumeration eNum = request.getParameterNames();
    while (eNum.hasMoreElements())
    {
         String key = eNum.nextElement().toString();
         try {
           String paramValue = URLDecoder.decode( request.getParameter(key), "UTF-8");
             //System.out.println("key : ["+key+ "] value [" + paramValue + "]");
             map.put(key, paramValue );
        } catch(Exception e) {
           e.printStackTrace();
        }
    }
    return map;
}

 

그런데 jQuery의 serialize 함수는 escape처리를 안 해 주기 때문에... 서버에서 변환할 때 한글이 깨진다.

jQuery의 serialize 함수는 encodeURIComponent() 함수 처리는 해 주는데, 여기서 escape() 처리를 더 해 준 것과의 차이를 보니....

% 를 %25 로 바꿔준것 밖에 없었다.

 

따라서 웹브라우저에서

str = $("#searchForm").serialize();

var str1 = str.r-place(/%/g,'%25');

oTable.fnReloadAjax( 'workListJson.do?'+str1 );

 

이 처리만 더 해주면 한글이 깨지지 않았다.

더 예외적인 케이스가 나올지는 모르겠지만, 일단은 이렇게 해서 jQuery의 serialize 함수도 쓰면서 한글이 깨지지 않도록 할 수 있었다.

 

728x90
반응형

'Carpe Programming > javascript' 카테고리의 다른 글

[javascript] window.open 옵션  (0) 2013.02.01
[정규식] 정규식 정리  (0) 2013.01.21
웹에서 한글(hwp) 파일 표출하기  (0) 2012.12.11
[javascript] 이미지 슬라이딩  (0) 2012.12.07
[datepicker] 달력 설정  (0) 2012.10.23