Search Results for '자바스크립트'

ATOM Icon

1 POSTS

  1. 2009/01/13 json data를 이용한 동적 table 만들기. by SADBLUE

json data를 이용한 동적 table 만들기.

model sample

<?
    $data = "[";
    $data .= "{" . "\"no\" : '1793', \"gw_user_info_no\" : '230',\"gw_board_info_no\" : '43',\"title\" : '[메신저] -제안- 채팅 저장 기능 업글',\"name\" : '이정훈',\"readnum\" : '9',\"write_datetime\" : '2009-01-12 11:07:23',\"write_date\" : '09-01-12',\"new_img\" : 'Y',\"poll_img\" : 'N',\"hidden_key\" : 'N',\"depth\" : '0',\"del_flag\" : 'N',\"board_name\" : '메신저 버그/제안',\"board_type\" : 'N', \"attach_cnt\" : '0', \"reply_cnt\" : '0', \"down_cnt\" : '', \"startPage\" : '2', \"current_user_level\" : '2'" . "},";
    $data .= "{" . "\"no\" : '1793', \"gw_user_info_no\" : '230',\"gw_board_info_no\" : '43',\"title\" : '[메신저] -제안- 채팅 저장 기능 업글',\"name\" : '이정훈',\"readnum\" : '9',\"write_datetime\" : '2009-01-12 11:07:23',\"write_date\" : '09-01-12',\"new_img\" : 'Y',\"poll_img\" : 'N',\"hidden_key\" : 'N',\"depth\" : '0',\"del_flag\" : 'N',\"board_name\" : '메신저 버그/제안',\"board_type\" : 'N', \"attach_cnt\" : '0', \"reply_cnt\" : '0', \"down_cnt\" : '', \"startPage\" : '2', \"current_user_level\" : '2'" . "},";
    $data .= "{" . "\"no\" : '1793', \"gw_user_info_no\" : '230',\"gw_board_info_no\" : '43',\"title\" : '[메신저] -제안- 채팅 저장 기능 업글',\"name\" : '이정훈',\"readnum\" : '9',\"write_datetime\" : '2009-01-12 11:07:23',\"write_date\" : '09-01-12',\"new_img\" : 'Y',\"poll_img\" : 'N',\"hidden_key\" : 'N',\"depth\" : '0',\"del_flag\" : 'N',\"board_name\" : '메신저 버그/제안',\"board_type\" : 'N', \"attach_cnt\" : '0', \"reply_cnt\" : '0', \"down_cnt\" : '', \"startPage\" : '2', \"current_user_level\" : '2'" . "},";
    $data .= "{" . "\"no\" : '1793', \"gw_user_info_no\" : '230',\"gw_board_info_no\" : '43',\"title\" : '[메신저] -제안- 채팅 저장 기능 업글',\"name\" : '이정훈',\"readnum\" : '9',\"write_datetime\" : '2009-01-12 11:07:23',\"write_date\" : '09-01-12',\"new_img\" : 'Y',\"poll_img\" : 'N',\"hidden_key\" : 'N',\"depth\" : '0',\"del_flag\" : 'N',\"board_name\" : '메신저 버그/제안',\"board_type\" : 'N', \"attach_cnt\" : '0', \"reply_cnt\" : '0', \"down_cnt\" : '', \"startPage\" : '2', \"current_user_level\" : '2'" . "},";
    $data .= "{" . "\"no\" : '1793', \"gw_user_info_no\" : '230',\"gw_board_info_no\" : '43',\"title\" : '[메신저] -제안- 채팅 저장 기능 업글',\"name\" : '이정훈',\"readnum\" : '9',\"write_datetime\" : '2009-01-12 11:07:23',\"write_date\" : '09-01-12',\"new_img\" : 'Y',\"poll_img\" : 'N',\"hidden_key\" : 'N',\"depth\" : '0',\"del_flag\" : 'N',\"board_name\" : '메신저 버그/제안',\"board_type\" : 'N', \"attach_cnt\" : '0', \"reply_cnt\" : '0', \"down_cnt\" : '', \"startPage\" : '2', \"current_user_level\" : '2'" . "}";
    $data .= "]";

    $return_data = "{";
    $return_data .= "\"resultCode\" : 'OK',";
    $return_data .= "\"row\" : '5',";
    $return_data .= "\"column\" : '5',";
    $return_data .= "\"result\" : " . $data . ",";
    $return_data .= "\"message\" : '',";
    $return_data .= "\"layerID\" : ''";
    $return_data .= "}";

    echo($return_data);
?>

view xml definition
<?xml version="1.0" encoding="UTF-8" ?>
<gabia>
    <tables>
        <notice>
            <rowCss>noticeRow1</rowCss>
            <rowCss>noticeRow2</rowCss>
            <rowCss>noticeRow3</rowCss>
            <row><![CDATA[noticeTitle^^<a href="#no#">#title#</a>]]></row>
            <row><![CDATA[noticeAuthor^^#name#]]></row>
            <row><![CDATA[noticeCountHead^^#readnum#]]></row>
            <row><![CDATA[noticeDateHead^^#write_date#]]></row>
            <row><![CDATA[noticeBoardHead^^#board_name#]]></row>
        </notice>
    </tables>
</gabia>

control class

/********************************************************************************
참조 : http://phpschool.com/gnuboard4/bbs/board.php?bo_table=tipntech&wr_id=51107&sca=%BD%BA%C5%A9%B8%B3%C6%AE&sfl=wr_subject&stx=xml&sop=and
prototype을 이용한 xml parser class
********************************************************************************/

var xmlParser = Class.create();
xmlParser.prototype = {
    initialize: function()
    {
    },
    getNode: function (xml, tag)
    { // 싱글노드
        return xml.getElementsByTagName(tag)[0];
    },
    getNodeAll: function (xml, tag)
    { // 멀티노드
        return xml.getElementsByTagName(tag);
    },
    getValue: function (xml)
    { // 노드값 가져오기
        try
        {
            return xml.firstChild.nodeValue;;
        }
        catch(E)
        {
            alert(E);
        }
    }
};

/********************************************************************************
    ajax를 이용한 json data를 parsing해서 table을 그리는 class
    작성자 : 이정훈 (ljhoon@gabia.com)
    작성일 : 2009.01.13
********************************************************************************/

var tableXML = "http://local.inmail.co.kr/test.xml";

/********************************************************************************
 stCell : td를 구성하기 위한 기본 정보를 갖게 되는 구조체 성격의 Class
     만약 td에 정의 해야 할 속성이 늘어나면 xml에 ^^ 구분자를 이용해서
     추가를 하고 stCell class에도 속성을 추가 해 주면 된다.
********************************************************************************/
var stCell = Class.create();
stCell.prototype = {
    cssName : null,
    cellData : null,

    initialize : function(pData)
    {
        if (pData.length < 1)
        {
            this.setNullData();
            return;
        }

        this.cssName = pData[0];
        this.cellData = pData[1];
    },

    getCss : function()
    {
        return this.cssName;
    },

    getData : function()
    {
        return this.cellData;
    },

    setData : function(pValue)
    {
        this.cellData = pValue;
    },

    setNullData : function()
    {
        this.cssName = "nodata";
        this.cellData = "nodata";
    }
};

/********************************************************************************
 stRow : td 배열을 갖게 되는 row 구조체 class
     row별 배경색이 다른 경우를 위해 css이름 속성을 갖는다.
********************************************************************************/
var stRow = Class.create();
stRow.prototype = {
    m_stCells : null,
    m_oCss : null,
    length : 0,

    initialize : function()
    {
        this.m_oCss = new Array();
        this.m_stCells = new Array();
    },

    insert : function(pCell)
    {
        this.m_stCells[this.m_stCells.length] = pCell;
        this.length++;
    },

    setCss : function(pCss)
    {
        if (typeof(pCss) != "Object")
            this.m_oCss[this.m_oCss.length] = pCss;
        else if (pCss.length > 1)
        {
            var cssCount = pCss.length;
            for (var i=0 ; i<cssCount ; ++i)
                this.m_oCss[cssCount + i] = pCss[i];
        }
    },

    getCell : function(pIndex)
    {
        if (this.m_stCells.length >= pIndex)
        {
            return this.m_stCells[pIndex];
        }
    },

    getColumnCount : function()
    {
        return this.m_stCells.length;
    },

    getCssCount : function()
    {
        return this.m_oCss.length;
    },

    getCss : function(pIndex)
    {
        if (this.m_oCss.length > pIndex)
            return this.m_oCss[pIndex];
        else
            return this.m_oCss[0];
    }
};

/********************************************************************************
 Table : stRow, stCell을 이용해 실제 Table row를 그리고 구조 정보 xml을 읽어온다.
********************************************************************************/
var Table = Class.create();
Table.prototype = Object.extend (new xmlParser, {
    m_nCol : 0,
    m_nRow : 0,
    m_oData : null,
    m_oTableID : null,
    m_oRowTemplate : null,
    m_oDefaultRowCss : null,
    xmlBuffer : null,
    m_oRows : null,
    m_bHeaderExist : true,

/********************************************************************************
 pData : json data
 pTableID : target table id
 pHeaderExist : 테이블 column별 제목이 있다면 true 없다면 false.
      table을 그리기 전에 true이면 1줄을 남기고 없다면 모든 row를 지운다.
********************************************************************************/
    initialize : function(pData, pTableID, pHeaderExist)
    {
        this.m_nColumn = pData.row;
        this.m_nRow = pData.column;
        this.m_oData = pData.result;
        this.m_oTableID = pTableID;
        this.m_bHeaderExist = pHeaderExist;

        this.loadXML();
    },

/********************************************************************************
 table 구조 xml을 읽어 오는 부분. 동기로 처리 했음.
********************************************************************************/
    loadXML : function()
    {
        new Ajax.Request(tableXML, {
            asynchronous: false,
            method: "get",
            onSuccess: function(xmlHttp)
            {
                try
                {
                    xmlBuffer = xmlHttp.responseXML;
                    return true;
                }
                catch(E)
                {
                    xmlBuffer = null;
                    alert("XML Load Fail : " + E);

                    return false;
                }
            },
            onFailure : function (request)
            {
                xmlBuffer = null;
                alert("Table Template XML Request Fail");
                return false;
            }
        });
    },

/********************************************************************************
 xml에 정의된 각 td별 설정을 읽어와 rowTemplate 객체를 만든다.
 row별 css정보도 여기서 설정한다. css가 명시된 수 만큼 적용된다.
********************************************************************************/
    getRowTemplate : function()
    {
        if (xmlBuffer == null)
            return ("table row Info is null");
        else
        {
            try
            {
                this.m_oRows = null;
                this.m_oRows = new stRow();

                var objectNode = this.getNode(xmlBuffer, this.m_oTableID);
                var cssTemp = this.getNodeAll(objectNode, "rowCss");

                for(var i=0 ; i<cssTemp.length ; ++i)
                    this.m_oRows.setCss(this.getValue(cssTemp[i]));

                var rowTemp = this.getNodeAll(objectNode, "row");

                for(var i=0 ; i<rowTemp.length ; ++i)
                {
                    var templateValue = this.getValue(rowTemp[i]);
                    this.m_oRows.insert(new stCell(templateValue.split("^^")));
                }
            }
            catch(E)
            {
                alert("Node select fail : " + E);
                return;
            }
        }
    },

/********************************************************************************
 실제로 table row를 생성 하는 부분
 row를 추가 하기 전에 기존에 그려진 모든 row를 지운다.
 json의 인덱스 명은 xml에서 명시한 delimiter명과 같아야 한다.
********************************************************************************/
    insertRow : function()
    {
        if ($(this.m_oTableID) == null)
        {
            alert("Base Table is null.");
            return;
        }

        if ($(this.m_oTableID).rows.length > 1)
        {
            if (this.m_bHeaderExist)
            {
                for(var i=($(this.m_oTableID).rows.length-1) ; i>0 ; --i)
                    $(this.m_oTableID).deleteRow(i);
            }
            else
            {
                for(var i=($(this.m_oTableID).rows.length-1) ; i>=0 ; --i)
                    $(this.m_oTableID).deleteRow(i);
            }
        }

        this.getRowTemplate();

        for(var i=0 ; i<this.m_nRow ; ++i)
        {
            var nLoopCount = 0;

            var row = $(this.m_oTableID).insertRow(-1);
            row.className = this.m_oRows.getCss( (i+1)%this.m_oRows.getCssCount() );

            for (var j=0 ; j<this.m_oRows.length ; ++j)
            {
                var c = row.insertCell(-1);
                var tempCell = this.m_oRows.getCell(nLoopCount).getData();

                for(var tempIndex in this.m_oData[i])
                {
                    var delimiter = new RegExp("#" + tempIndex + "#", "ig");
                    tempCell = tempCell.replace(delimiter, this.m_oData[i][tempIndex]);
                }

                c.innerHTML = tempCell;
                c.className = this.m_oRows.getCell(nLoopCount).getCss();
                nLoopCount++;
            }
        }
    }
});

구동 html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>test</title>
    <script language="javascript" type="text/javascript" src="/scripts/prototype.js"></script>
    <script language="javascript" type="text/javascript" src="/scripts/ajaxBasic.js"></script>
    <script language="javascript" type="text/javascript" src="/scripts/simpleXml.js"></script>
    <script language="javascript" type="text/javascript" src="/scripts/table.js"></script>
   
    <style type="text/css">
        table, div { float:left; position:relative; display:inline-block; padding:0; margin:0; }
       
        #list { width:800px; border:solid 1px #dddddd; }
        #list #notice {width:600px; font-size:11px; font-family : 맑은고딕, Lucida Grande, Verdana, Sans-serif;}
        #list #notice tr { height:20px; }
        #list #notice .noticeHeader {font-weight:bold; text-align:center;}
        #list #notice .noticeRow1 {border-bottom:solid 1px #dddddd; }
        #list #notice .noticeRow2 {border-bottom:solid 1px #dddddd; background-color:#dddddd; }
        #list #notice .noticeRow3 {border-bottom:solid 1px #dddddd; background-color:#aaaaaa; }
       
        #list #notice .noticeTitleHead {width:250px;}
        #list #notice .noticeDateHead {width:75px;}
        #list #notice .noticeCountHead {width:75px; text-align:right;}
        #list #notice .noticeAuthorHead {width:100px;}
        #list #notice .noticeBoardHead {width:100px;}
    </style>
</head>
<body>
<div>
    <div id="list">
        <table id="notice">
            <tr class="noticeHeader"><td class="noticeTitleHead">제목</td><td class="noticeAuthorHead">등록자</td><td class="noticeCountHead">조회수</td><td class="noticeDateHead">작성일</td><td class="noticeBoardHead">게시판</td></tr>
        </table>
    </div>
</div>
<input type="button" value="test" onclick="getData();">

<script language="javascript">
    function getData()
    {
        getAjaxData('/test.php', "", rowAppend);
    }
   
    function rowAppend(pValue)
    {
        var objTable2 = new Table(pValue, "notice", false);
        objTable2.insertRow();
    }
</script>
   
</body>

</html>

Posted by SADBLUE

2009/01/13 14:37 2009/01/13 14:37
, , , , ,
Response
5 Trackbacks , 0 Comments
RSS :
http://sadblue.com/rss/response/225

Trackback URL : http://sadblue.com/trackback/225

Trackbacks List

  1. Натяжные потолки установка

    Tracked from Натяжные потолки установка 2023/05/05 17:33 Delete

    As if nothing had happened... :: json data를 이용한 동적 table 만들기.

  2. Входная дверь внутри

    Tracked from Входная дверь внутри 2023/09/23 19:36 Delete

    As if nothing had happened... :: json data를 이용한 동적 table 만들기.

  3. Купить металлопластиковые окна в кривом Роге

    Tracked from Купить металлопластиковые окна в кривом Роге 2023/09/29 00:30 Delete

    As if nothing had happened... :: json data를 이용한 동적 table 만들기.

  4. Потолки натяжные отзывы

    Tracked from Потолки натяжные отзывы 2023/11/21 08:58 Delete

    As if nothing had happened... :: json data를 이용한 동적 table 만들기.

  5. Ортопедические матрасы кривой рог цены

    Tracked from Ортопедические матрасы кривой рог цены 2023/11/22 14:05 Delete

    As if nothing had happened... :: json data를 이용한 동적 table 만들기.


블로그 이미지

난 평생 녹지 않는 눈 속에서 살아갈게... 너와 본 꿈을 잊지 않도록.... As if nothing had happened...

- SADBLUE

Notices

Archives

Authors

  1. SADBLUE

Recent Trackbacks

  1. 드디어 내 손에!!! Clean out. As if nothing h... 2010

Calendar

«   2024/11   »
          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

Site Stats

Total hits:
2243257
Today:
1236
Yesterday:
1044