div에다가 createElement로 노드들을 추가하면 div의 높이가 변하는게 당연해 보이는데 - IE6에서는 변한다
Firefox, Crome 등의 브라우저에서는 초기에 설정된 값이 변하지 않는다.

여기저기 뒤져서
1. html, body, div의 height를 100%로 주면 된다 - http://www.webmasterworld.com/forum83/200.htm
  하지만 이건 창 크기가 변할 때 쓰는 듯하고.(element가 추가되는 경우에는 제대로 div가 커지지 않았음)

2. min-height를 주면 된다 - http://forum.standardmag.org/viewtopic.php?id=2239
  안된다 ㅠ.ㅠ

등의 글을 참고했지만 안됨...

모르겠음 ㅠ.ㅠ

그냥 추가되는 노드의 수 만큼 직접 height를 수정하는게 나을 듯.
출처: http://srchun.springnote.com/pages/4799503

브라우저 별로 크기가 다르다는 얘기..

scrollHieght 찾다가 나왔음...
        var el = document.createElement("span");
        el.setAttribute("title", key);
        el.setAttribute("class", "dpCatLabel");
      //el.setAttribute("onclick", "alert('TEST');"); // DOESN'T WORK. onclick is not attribute.
      el.onclick=function(){alert("TEST");};
        var txt = document.createTextNode(label);
        el.appendChild(txt);

onclick 등은 이벤트라서 setAttribute로 붙일 수 없고,
el.onclick=function;  으로 붙이자.

[jQuery] jQuery를 이용한 ajax

프로그래밍/Web 2009. 12. 16. 11:20 Posted by galad
function ajaxGetDpCatList() {
    //alert("ajax로 전체 전시 카테고리 정보 얻기");
    //alert($(this).attr("title"));
   
    var selectedCatId = $(this).attr("title");
    $("#selectedCatId").val(selectedCatId);
    //alert($("#selectedCatId").val());
   
    $.ajax({
        url: '${pageContext.request.contextPath}/categoryMapping/getDpCatList.omp',
        type: 'POST',
        dataType: 'json',
        timeout: 5000,
        error: function(){
            alert('전시 카테고리 정보를 얻는 중에 오류가 발생했습니다.');
        },
        success: function(data){
            //alert(data);
            //alert(data.dpCatList[0].key + " " + data.dpCatList[0].value);
            showDpCatList(data);
        }
    });
}

- json 형식으로 결과를 받겠다 해놓고, 결과가 json형식에 안맞아도 error.
- timeout 시간이 넘어가도 error. 처음엔 개발장비서 할 떄 계속 에러나서 원인을 못찾았었음. 주의할 것.

$.ajax외에도 $.post 같은 좀 더 간단한 jQuery 메소드가 있음.
http://www.ibm.com/developerworks/kr/library/wa-jquery3/

[javascript] HTML DOM 지우기

프로그래밍/Web 2009. 12. 16. 10:25 Posted by galad
createElement로 생성한 노드들을 지울때, 특정 노드 밑에 딸린 노드들을 몽창 한번에 지우는 메소드가 없는 건지 못찾은 건지,
아무튼 parentNode에 딸린 노드들을 전부 찾아서(getElementsByTag), for 루프 돌면서 지우는데 절반만 지워져서 헤매다가 원인을 찾았음

function deleteNodes(parentNode, tag) {
    var nodes = parentNode.getElementsByTagName(tag);
    var length = nodes.length;
    
    // 이건 nodes가 실시간으로 줄어들면서 length 자체가 줄어든다.
    // 따라서 아래의 for문에서 기존 nodes의 갯수만큼 루핑하면서 0번만 계속 지움.
    // i번을 삭제하면 stack overflow 남
    /*for(var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        parentNode.removeChild(node);
    }*/
    
    for(var i = 0; i < length; i++) {
        var node = nodes[0];
        parentNode.removeChild(node);
    }
}

위에 써놓은 것처럼

for(var i = 0; i < nodes.length; i++) {
    var node = nodes[i];
    parentNode.removeChild(node);
}

nodes.length로 한계치를 정하면 for 문 안에서 자식 노드를 하나씩 지울 때마다 nodes.length 가 하나씩 줄어든다. 실시간 반영?!
그래서 length를 따로 저장하고 맨 처음 것만 계속 지웠음.

'프로그래밍 > Web' 카테고리의 다른 글

[javascript] HTML DOM 생성 후 이벤트 추가  (0) 2009.12.16
[jQuery] jQuery를 이용한 ajax  (0) 2009.12.16
[jQuery] jQuery를 이용한 팝업. div, layer  (0) 2009.12.16
[json] json 사용법  (0) 2009.12.15
[html] html 특수기호  (3) 2009.09.08
출처: http://whdrnr01.textcube.com/7?t=c&i=0

jQuery를 이용해서, div의 설정 변경을 통한 레이어 팝업.
ajax랑 함께 쓰면, ajax를 이용해서 데이터를 얻어온 후, div의 안에 원하는 형태로 데이터를 넣고 나서 보여주는 형식이 될 듯.

소스출처: http://yensdesign.com/tutorials/popupjquery/

/**
 * jQuery를 이용한 초기 설정
 */
$(document).ready(function() {
    // 마우스 오버 시 배경색 반전
    $(".catLabel1").hover(
        function() { // hover 시
            $(this).css({"background-color":"yellow", "font-weight":"bolder" });
        },
        function() { // out 시
            $(this).css({"background-color":"white", "font-weight":"normal" });
        }
    );

    $(".catLabel2").hover(
            function() { // hover 시
                $(this).css({"background-color":"yellow", "font-weight":"bolder" });
            },
            function() { // out 시
                $(this).css({"background-color":"white", "font-weight":"normal" });
            }
        );
   
    // 표준분류 선택 시 전시 카테고리 목록을 표시한다.
    $(".catLabel1").click(showAlert);
    $(".catLabel2").click(ajaxGetDpCatList);
   
    //CLOSING POPUP
    //Click the x event!
    /*$("#popupContactClose").click(function(){
        disablePopup();
    });*/
    //Click out event!
    $("#backgroundPopup").click(function(){
        disablePopup();
    });
    //Press Escape event!
    $(document).keypress(function(e){
        if(e.keyCode==27 && popupStatus==1){
            disablePopup();
        }
    });
});

/**
 * 표준 분류의 대분류 선택 시 경고 메시지
 */
function showAlert() {
    alert("표준 카테고리의 중분류를 선택해 주세요.");
}

/**
 * ajax로 전시 카테고리 목록 얻어오기
 */
function ajaxGetDpCatList() {
    //alert("ajax로 전체 전시 카테고리 정보 얻기");
    //alert($(this).attr("title"));
   
    var selectedCatId = $(this).attr("title");
    $("#selectedCatId").val(selectedCatId);
    //alert($("#selectedCatId").val());
   
    $.ajax({
        url: '${pageContext.request.contextPath}/categoryMapping/getDpCatList.omp',
        type: 'POST',
        dataType: 'json',
        timeout: 5000,
        error: function(){
            alert('전시 카테고리 정보를 얻는 중에 오류가 발생했습니다.');
        },
        success: function(data){
            //alert(data);
            //alert(data.dpCatList[0].key + " " + data.dpCatList[0].value);
            showDpCatList(data);
        }
    });
}

/**
 * 전시 카테고리 목록 표시
 */
function showDpCatList(data) {
    //alert($("#selectedCatId").val());
    //alert(data.dpCatList.length);

    var dpCatListPopup = document.getElementById("dpCatListPopup");

    // dpCatListPopup 의 내용을 비움. 안하면 계속 늘어남
    deleteNodes(dpCatListPopup, "span");
    deleteNodes(dpCatListPopup, "br");

    // 전시 카테고리 표시용 목록 만들기
    var list = data.dpCatList;
    for(var i = 0; i < list.length; i++) {
        var key = list[i].key;
        var label = list[i].value;

        var el = document.createElement("span");
        el.setAttribute("title", key);
        el.setAttribute("class", "dpCatLabel");
        //el.setAttribute("onclick", "alert('TEST');"); // DOESN'T WORK. onclick is not attribute.
        el.onclick=function(){alert("TEST");};
        var txt = document.createTextNode(label);
        el.appendChild(txt);

        dpCatListPopup.appendChild(el);
        dpCatListPopup.appendChild(document.createElement("br"));
    }

    setPopupPosition();
    loadPopup();
}

function deleteNodes(parentNode, tag) {
    var nodes = parentNode.getElementsByTagName(tag);
    var length = nodes.length;
   
    // 이건 nodes가 실시간으로 줄어들면서 length 자체가 줄어든다.
    // 따라서 아래의 for문에서 기존 nodes의 갯수만큼 루핑하면서 0번만 계속 지움.
    // i번을 삭제하면 stack overflow 남
    /*for(var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        parentNode.removeChild(node);
    }*/
   
    for(var i = 0; i < length; i++) {
        var node = nodes[0];
        parentNode.removeChild(node);
    }
}

//0 means disabled; 1 means enabled;
var popupStatus = 0;

/**
 * set popup position
 */
function setPopupPosition(){
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.scrollHeight; //clientHeight;
    var popupHeight = $("#dpCatListPopup").height();
    var popupWidth = $("#dpCatListPopup").width();
   
    //centering
    $("#dpCatListPopup").css({
        "position": "absolute",
        "top": 0, //windowHeight/2-popupHeight/2,
        "left": windowWidth/2-popupWidth/2
    });

    //only need force for IE6
    $("#backgroundPopup").css({
        "height": windowHeight
    });
   
}

function loadPopup(){
    //loads popup only if it is disabled
    if(popupStatus==0){
        $("#backgroundPopup").css({
            "opacity": "0.7"
        });
        $("#backgroundPopup").fadeIn("slow");
        $("#dpCatListPopup").fadeIn("slow");
        popupStatus = 1;
    }
}

function disablePopup(){
    //disables popup only if it is enabled
    if(popupStatus==1){
        $("#backgroundPopup").fadeOut("slow");
        $("#dpCatListPopup").fadeOut("slow");
       
        popupStatus = 0;
    }
}

setPopupPosition() 으로 위치 설정.
loadPopup() 으로 보이기
disablePopup() 으로 숨기기

backgroundPopup 랑 dpCatListPopup 는 div의 id.

'프로그래밍 > Web' 카테고리의 다른 글

[jQuery] jQuery를 이용한 ajax  (0) 2009.12.16
[javascript] HTML DOM 지우기  (0) 2009.12.16
[json] json 사용법  (0) 2009.12.15
[html] html 특수기호  (3) 2009.09.08
[servlet] servlet  (0) 2009.09.04

[json] json 사용법

프로그래밍/Web 2009. 12. 15. 11:23 Posted by galad
출처: http://mogaji.springnote.com/pages/314716

{"payCodeList":
        [
            {"key":"PD00290","value":"무료"},
            {"key":"PD00292","value":"기간정액제"}
        ]
}

key:value 쌍만으로는 안될때는 이런 식으로...

아래는 위의 출처 내용을 보관을 위해 발췌했음.

JSON은 무엇인가?

  1. JSON은 무엇인가?
    • 경량의 데이타 교환 포맷이다.
      > XML과 비교한다.
    • 간단한 포맷
      > 사람들을 위해 읽고 쓰기가 쉽다.
      > 기계들을 위해 분석과 생성이 쉽다.
    • JSON은 텍스트 포맷이다.
      > 언어에 독립적으로 프로그래밍된다.
      > 프로그래머들에게 잘 알려진 C,C++,C#,Java,JavaScript,Perl,Pyton을 포함하는 C와 유사한 언어로 모여서 사용된다.

  2. XML을 넘어 왜 JSON인가?
    • on-the-wire(선을 통한) 데이타 포맷인 XML보다 가볍고 빠르다.
    • JSON 오브젝트는 XML 데이타가 타입이 없는데 비해 타입을 가진다.
      > JSON types : string, number, array, boolean
      > XML 데이타는 모두 String 이다.
    • JavaScript 코드를 위해 Native 코드포맷이다.
      > Data는 사용자의 JavaScript코드 안에서 JSON 객체에 접근이 쉽다.
      XML 데이타가 해석과 장황한 DOM API를 통해 변수에 접근하는 것을 필요로 하는데 비해
      > 회수한 값들은 사용자의 자바스크립트 안의 객체속성에서 읽기가 쉽다.

  3. JSON은 어디에서 사용되는가?
    • 구성정보를 나타낸다.
    • 통신 프로토콜을 실행한다.

JSON Object

  1. JSON 구조
    • name/value 쌍으로 구성된다.
      > 여러가지의 언어들에서 object, record, struct, dictionary, hashtable, 키를 가지는 리스트, 배열집합 처럼 얻어진다.
    • 값들이 리스트는 순서가 있다.
      > 대부분의 언어들에서 array, vector, list, sequence 처럼 얻어진다.
    • JSON은 대부분의 지금의 언어를 통해 일반적인 데이타구조들이 지원된다.

  2. JSON Object 표기법
    • JSON Object는 name/value 쌍의 set은 순서가 없다.
    • JSON Object는 { 로 시작하고 } 로 끝난다.
    • 각각의 이름은 : 와 ,로 구분된 name/value 쌍의 형식을 따른다.

  3. JSON과 JavaScript
    • JSON은 JavaScript의 객체 문자 표기의 부분집합이다.
      > JSON은 JavaScript안에서 혼란스럽거나 야단스럽지 않게 사용될 수 있다.

  4. JSON Object 예제
     
    var myJSONObject = {"bindings": [
    {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
    {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
    {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
    ]
    };
    • 위의 예에서, JSON JavaScript 객체는 세개의 객체를 포함한 배열을 갖고있는, 각각은 "ircEvent","method","regex" 멤버들을 포함한 하나의 멤버 "bindings"를 포함하여 생성된다.
    • 멤버들은 점(.) 이나 그아래 지시자들로 회수 할수 있다.
       
      myJSONObject.bindings[0].method // "newURI"
  5. JavaScript 코드안에서 Text를 Object로 변환하기
     
    var myObject = eval('(' + myJSONtext + ')');
    • eval() 함수를 사용하여, JSON text를 JSON 객체로 변환한다.
      > eval()은 JavaScript 컴파일러에서 실행한다.
      > JSON은 JavaScript의 서브셋으로 적합하다. 컴파일러는 text를 정확하게 변환하고, 객체 구조를 만든다.

  6. 보안 & JSON Parser
    // Include http://www.json.org/json.js
    var myObject = myJSONtext.parseJSON();
    • eval()은 컴파일 할 수 있고, 어떤 JavaScript 프로그램에서도 실행된다. 그래서 보안 이슈들(cross-site scripting)을 가질 수 있다.
      > 소스를 신뢰할 수 있을때, eval()을 사용해라.
    • 보안이 염려될 때 - 소스를 신뢰할 수 없을때 - JSON parser를 사용하는게 낫다.
      > JSON parser는 JSON text를 승인할 수 있다. 그래서 좀더 안전하다.

  7. Object를 Text로 변환하기
     
    var myJSONText = myObject.toJSONString();
    • 사용자는 JSON 객체를 JSON text로 변환할 수 있다.
    • JSON은 주기적 데이타 구조를 지원하지 않는다.

      > Do not give cyclical structures to the JSON stringifier
      > 주기적 구조들을 JSON stringfier로 줄수 없다

Java 안에서의 JSON

  1. 자바 개발자를 위한 JSON Tools
    • Parser
      > JSON text 파일들을 해석하고, 그들을 자바 모델로 변환한다.
    • Renderer
      > 자바를 text로 표현하게 한다.
    • Serializer
      > 알기쉬운 POJO clusters를 JSON 표현으로 나열한다.
    • Validator
      > JSON 스키마를 사용하여 JSON 파일의 내용을 유효한지 체크한다.

  2. JSONObject 자바 클래스
    • JSONObject의 name/value 쌍의 집합은 순서가 없다.
    • put 메소드는 객체로 name/value쌍을 add 한다.
    • text들은 JSON syntax rules을 정확히 따른 toString 메소드에 의해 만들어진다.
       
      myString = new JSONObject().put("JSON", "Hello, World!").toString();
      // myString is {"JSON": "Hello, World"}

클라이언트와 서버사이드 양쪽에서 JSON 데이타를 주고 받는 방법

  1. 서버사이드에서 JSON 데이타를 생성하고 보내는 방법
    • JSONObject 자바 객체를 생성한다.
    • put 메소드를 사용하여 name/value 쌍을 add한다.
    • toString 메소드를 사용하여 String 타입으로 변환한다.
      그리고 "text/xml" 또는 "text/plain" 처럼 content-type과 함께 클라이언트로 보낸다.
       
      myString = new JSONObject().put("JSON",toString();
      // myString is {"JSON": "Hello, World"}
  2. 클라이언트 사이드에서 JSON 데이타를 받는 방법
    • JSON 데이타는 String 처럼 반환된다.
    • JavaScript 코드안에서 JSON 객체를 만들수 있게 eval()을 호출한다.
      > var JSONdata = eval(req.response.Text);
    • 사용자는 한번 JSON 객체를 가질수 있고, 객체의 속성들에 접근하기 위해 . 을 사용할 수 있다.
       
      var name = JSONdata.name;
      var address = JSONdata.addresses[3];
      var streetname = JSONdata.addresses[3].street;
    • 클라이언트 사이드에서 JSON 데이타를 생성하고 보내는 방법
    • JSON 자바스크립트 객체를 생성한다.
    • XMLHttpRequest객체의 open 메소드 안에 "POST" HTTO 메소드를 사용한다.
    • XMLHttpRequest객체의 send 메소드안에서 JSON 자바스크립트 객체를 패스한다.
       
      var carAsJSON = JSON.stringify(car);
      var url = "JSONExample?timeStamp=" + new Date().getTime();
      createXMLHttpRequest();
      xmlHttp.open("POST", url, true);
      xmlHttp.onreadystatechange = handleStateChange;
      xmlHttp.setRequestHeader("Content-Type",
      "application/x-www-form-urlencoded");
      xmlHttp.send(carAsJSON);
  3. 서버사이드에서 JSON 데이타를 받는 방법
    • String 타입처럼 JSON데이타를 읽는다.
    • string으로부터 JSONObject 자바객체를 생성한다.
       
      String json = readJSONStringFromRequestBody(request);
      //Use the JSON-Java binding library to create a JSON object in Java
      JSONObject jsonObject = null;
      try {
      jsonObject = new JSONObject(json);
      }
      catch(ParseException pe) {
      }

리소스들

  1. JSON 리소스들
    • Introducing JSON
    > http://www.json.org/
    • JSON in JavaScript
    > http://www.json.org/js.html
    • JSON in Java
    > http://www.json.org/java/index.html

참고문헌

문서에 대하여

최초작성자 : 난다
최초작성일 : 2007년 4월 17일
버전 : 0.1
문서이력 :

  • 2007년 4월 17일 난다 문서 최초 생성

    [출처] JSON|작성자 agileman


'프로그래밍 > Web' 카테고리의 다른 글

[javascript] HTML DOM 지우기  (0) 2009.12.16
[jQuery] jQuery를 이용한 팝업. div, layer  (0) 2009.12.16
[html] html 특수기호  (3) 2009.09.08
[servlet] servlet  (0) 2009.09.04
[jQuery] jQuery 예제 02  (0) 2009.09.04