DevEnjoy

One Step Closer

jquery

jQuery Ajax에서 json Array 직렬화

2014년 10월 23일 by YongPwi 7 Comments

jQuery Ajax에서 data를 json 방식으로 Array를 전달하려고,,,

꽤 많은 삽질을 했다,,,

역시 안쓰면 금방 까먹는것 같다,,,

별다른건 없는데 form에 있는 데이터가 아니어서 강제적으로 json형태로 만들어 주고서

ajax call 하기만 하면 되는데 왜 안될까,,,

json 은 한개의 key 값으로 배열형태로 넘겼다,,,

그런데 server 단에서 getParameterNames을 받질 못하는 상황이 발생하였다,,,

넘어온 파라미터와 값을 찍어보니 내가 의도한 파라미터 명으로 넘어가지 않았다,,,

난 ‘key’ 명으로 배열로 받을거라 생각 했는데,,,

실제 넘어온건 ‘key[]’ 명으로 넘어왔다,,,

내가 json 데이터를 잘못 만들었나 싶어서 수 많은 삽질을 했다,,,

삽질과 구글링을 해보다 jquery.ajax api를 다시 좀보니,,,

data에 값이 배열인 경우에는 동일한 키값을 같는 직렬화 세팅을 해주는 문구가 있었다,,,

젠쟝,,,

결국은 하위 코드 주석처리 해놓은 traditional: true 를 추가해주니 의도한대로 ‘key’ 명으로 배열로 받을수 있었다,,,

사실 jQuery.param도 보긴 했는데,,,

꼼꼼하게 안보고 안된다는 생각에 무한 삽질 시간이 좀 후회스럽다,,,

jquery 1.4부터인가 바뀐거 같은데,,,

내가 마지막으로 써본 버전이 몇이던가,,,

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
32
33
34
35
var params = [];
var listSize = 5;
   for (var nRow = 0; nRow < listSize; nRow++) {
      params.push(nRow);
   }
$.ajax({
     url: callUrl,
     type: 'POST',
     data: {'key':params},
     dataType: 'json',
     //traditional: true,
     success: function (r) {
         
         });
     },
     error: function (xhr, status, error) {
                alert(xhr.status);
                alert(error);
     }  
});

//server단 확인
Enumeration em = request.getParameterNames();
while(em.hasMoreElements()){
    String parameterName = (String)em.nextElement();
    String parameterValue = request.getParameter(parameterName);
    String[] parameterValues = request.getParameterValues(parameterName);
    if(parameterValues != null){
         for(int i=0; i< parameterValues.length; i++){
             System.out.println("array_" + parameterName + "=" + parameterValues[i]);
         }
    } else {
         System.out.println(parameterName + "=" + parameterValue;
    }
}
Posted in: Javascript, Programing Tagged: ajax, array, jquery, json, traditional

jquery .attr() .prod() 차이

2014년 1월 23일 by YongPwi 6 Comments

현재 운영 중인 시스템이 오래되다 보니 jquery를 정책상 사용하고 있지 않다. (물론 군데군데 쓰인 곳은 있음)

운영 정책을 지키는 편이어서 사용 안 하고 있었는데 얼마 전 jquery 기반 editor를 사용한 page 작업 중 뇌가 다시 쫀쫀해 졌다.

기존에 내가 알고 있던 속성에 대한 핸들링은 거의 .attr()을 사용하였다.

jquery 둘러보던 중에 .attr() .prod() 가 1.6버전부터 구분되어서 사용되고 있다는걸 이제 보았다. (반성하자,,,)

1.6 이전까지는 속성(attribute)과 프로퍼티(property)를 같이 사용하였지만 이후부터는 명시적으로 구분해서 사용한다.

 

 Code  Description(return)
elem.checked  true (Boolean) Will change with checkbox state
$( elem ).prop( “checked” )  true (Boolean) Will change with checkbox state
elem.getAttribute( “checked” )  “checked” (String) Initial state of the checkbox; does not change
$( elem ).attr( “checked” ) (1.6)  “checked” (String) Initial state of the checkbox; does not change
$( elem ).attr( “checked” ) (1.6.1+)  “checked” (String) Will change with checkbox state
$( elem ).attr( “checked” ) (pre-1.6)  true (Boolean) Changed with checkbox state

 

1
2
3
4
5
6
7
8
9
10
11
<input type="checkbox" name="agreement" />
<a id="test" href="test2">주소</a>

<script type="text/javascript">
   alert($('[name=agreement]').prop('checked'));   // true or false
   alert($('[name=agreement]').attr('checked'));   // checked or undefined
   
   var link = $('#test');
   alert(link.attr('href'));   // test2
   alert(link.prop('href'));   // http://localhost(절대주소)/test2
</script>

상위 코드 처럼 두개의 결과값은 다르게 나타난다.

이 두개의 메소드는 취급하는 정보가 다르다.

.attr()는HTML의 속성(attribute)을 .prop()는 JavaScript의 프로파티(property)를 취급하는 메소드이다.

그냥 “되네~!” 하고 넘어갔던 내용인데,,, 오늘도 다시 한번 반성하자.

Posted in: Javascript, Programing Tagged: .attr(), .prod(), jquery

Calendar

3월 2023
일 월 화 수 목 금 토
« 4월    
 1234
567891011
12131415161718
19202122232425
262728293031  

Recent Posts

  • ubuntu bastion 설정
  • Spring Boot properties 암호화
  • Git Repository Bitbucket과 Issue Tracker Redmine 연동 설정
  • Spring Security 동일 session 제어
  • Spring @Mock, @Mockbean, @InjectMock

Recent Comments

  • pzotov (Ubuntu 14.04에서 Sonarqube 6.7.1 service 등록)
  • cours de theatre paris (AWS ELB와 Auto Scaling 연동, nginx)
  • bayern munich (IntelliJ EAP Font rendering)
  • camiseta del chelsea (OS X에서 APP 아이콘 변경)
  • cheap football shirts replica (jQuery Ajax에서 json Array 직렬화)

Copyright © [the-year] [site-link].

Powered by [wp-link] and [theme-link].