Where The Streets Have No Name

ajax에서 base64를 이용한 한글 전송 본문

Developement/Web

ajax에서 base64를 이용한 한글 전송

highheat 2008. 3. 26. 14:43
출처 : http://darksniper.springnote.com/pages/743356

var ajax = {};
ajax.xhr = {};

ajax.xhr.Request = function(url, params, callback, method) {
    this.url = url;
    this.params = params;
    this.callback = callback;
    this.method = method;
    this.send();
}
ajax.xhr.Request.prototype = {
    getXMLHttpRequest: function() {
        if (window.ActiveXObject) {
            try {
                return new ActiveXObject("Msxml2.XMLHTTP");
            } catch(e) {
                try {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                } catch(e1) { return null; }
            }
        } else if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        } else {
            return null;
        }       
    },
    send: function() {
        this.req = this.getXMLHttpRequest();
       
        var httpMethod = this.method ? this.method : 'GET';
        if (httpMethod != 'GET' && httpMethod != 'POST') {
            httpMethod = 'GET';
        }
        var httpParams = (this.params == null || this.params == '') ?
                         null : this.params;
       
        var httpUrl = this.url;
        if (httpMethod == 'GET' && httpParams != null) {
            httpUrl = httpUrl + "?" + httpParams;
        }
        this.req.open(httpMethod, httpUrl, true);
        this.req.setRequestHeader(
            'Content-Type', 'application/x-www-form-urlencoded');
        var request = this;
        this.req.onreadystatechange = function() {
            request.onStateChange.call(request);
        }
        this.req.send(httpMethod == 'POST' ? httpParams : null);
    },
    onStateChange: function() {
        this.callback(this.req);
    }    
   
}

 

//이벤트 부분
ajax.Event = {};
ajax.Event.addListener = function(element, name, observer, useCapture) {
    useCapture = useCapture || false;

    if (element.addEventListener) {
        element.addEventListener(name, observer, useCapture);
    } else if (element.attachEvent) {
        element.attachEvent('on' + name, observer);
    }
}
ajax.Event.removeListener = function(element, name, observer, useCapture) {
    useCapture = useCapture || false;
   
    if (element.removeEventListener) {
        element.removeEventListener(name, observer, useCapture);
    } else if (element.detachEvent) {
        element.detachEvent('on' + name, observer);
    }
}
ajax.Event.getTarget = function(event) {
    if (event == null) return null;
    if (event.target) return event.target;
    else if (event.srcElement) return event.srcElement;
    return null;
}
ajax.Event.getMouseXY = function(event) {
    var mouseX = event.clientX;
    var mouseY = event.clientY;
   
    var dd = document.documentElement;
    var db = document.body;
    if (dd) {
        mouseX += dd.scrollLeft;
        mouseY += dd.scrollTop;
    } else if (db) {
        mouseX += db.scrollLeft;
        mouseY += db.scrollTop;
    }
    return {x: mouseX, y: mouseY};
}
ajax.Event.isLeftButton= function(event) {
    return (event.which) ?
           event.which == 1 && event.button == 0 :
           (event.type == 'click') ? event.button == 0 : event.button == 1;
}
ajax.Event.isRightButton = function(event) {
    return event.button == 2;
}
ajax.Event.stopPropagation = function(event) {
    if (event.stopPropagation) {
        event.stopPropagation();
    } else {
        event.cancelBubble = true;
    }
}
ajax.Event.preventDefault = function(event) {
    if (event.preventDefault) {
        event.preventDefault();
    } else {
        event.returnValue = false;
    }
}
ajax.Event.stopEvent = function(event) {
    ajax.Event.stopPropagation(event);
    ajax.Event.preventDefault(event);
}
ajax.Event.bindAsListener = function(func, obj) {
    return function() {
        return func.apply(obj, arguments);
    }
}

ajax.GUI = {};
ajax.GUI.setOpacity = function(el, opacity) {
    if (el.filters) {
        el.style.filter = 'alpha(opacity=' + opacity * 100 + ')';
    } else {
        el.style.opacity = opacity;
    }
}
ajax.GUI.getStyle = function(el, property) {
    var value = null;
    var dv = document.defaultView;
   
    if (property == 'opacity' && el.filters) {// IE opacity
        value = 1;
        try {
            value = el.filters.item('alpha').opacity / 100;
        } catch(e) {}
    } else if (el.style[property]) {
        value = el.style[property];
    } else if (el.currentStyle && el.currentStyle[property]) {
        value = el.currentStyle[property];
    } else if ( dv && dv.getComputedStyle ) {
        // 대문자를 소문자로 변환하고 그 앞에 '-'를 붙인다.
        var converted = '';
        for(i = 0, len = property.length;i < len; ++i) {
            if (property.charAt(i) == property.charAt(i).toUpperCase()) {
                converted = converted + '-' +
                            property.charAt(i).toLowerCase();
            } else {
                converted = converted + property.charAt(i);
            }
        }
        if (dv.getComputedStyle(el, '').getPropertyValue(converted)) {
            value = dv.getComputedStyle(el, '').getPropertyValue(converted);
        }
    }
    return value;
}

ajax.GUI.getXY = function(el) {
    // el은 문서에 포함되어 있어야 하고, 화면에 보여야 한다.
    if (el.parentNode === null || el.style.display == 'none') {
        return false;
    }
   
    var parent = null;
    var pos = [];
    var box;
   
    if (document.getBoxObjectFor) { // gecko 엔진 기반
        box = document.getBoxObjectFor(el);
        pos = [box.x, box.y];
    } else { // 기타 브라우저
        pos = [el.offsetLeft, el.offsetTop];
        parent = el.offsetParent;
        if (parent != el) {
            while (parent) {
                pos[0] += parent.offsetLeft;
                pos[1] += parent.offsetTop;
                parent = parent.offsetParent;
            }
        }
        // 오페라와 사파리의 'absolute' postion의 경우
        // body의 offsetTop을 잘못 계산하므로 보정해야 한다.
        var ua = navigator.userAgent.toLowerCase();
        if (
            ua.indexOf('opera') != -1
            || ( ua.indexOf('safari') != -1 && this.getStyle(el, 'position') == 'absolute' )
        ) {
            pos[1] -= document.body.offsetTop;
        }
    }
   
    if (el.parentNode) { parent = el.parentNode; }
    else { parent = null; }
   
    // body 또는 html 이외의 부모 노드 중에 스크롤되어 있는
    // 영역이 있다면 알맞게 처리한다.
    while (parent && parent.tagName != 'BODY' && parent.tagName != 'HTML') {
        pos[0] -= parent.scrollLeft;
        pos[1] -= parent.scrollTop;
       
        if (parent.parentNode) { parent = parent.parentNode; }
        else { parent = null; }
    }
    return {x: pos[0], y: pos[1]};
}
ajax.GUI.getX = function(el) {
    return ajax.GUI.getXY(el).x;
}
ajax.GUI.getY = function(el) {
    return ajax.GUI.getXY(el).y;
}
ajax.GUI.getBounds = function(el) {
    var xy = ajax.GUI.getXY(el);
    return {
        x: xy.x,
        y: xy.y,
        width: el.offsetWidth,
        height: el.offsetHeight
    };
}
ajax.GUI.setXY = function(el, x, y) {
    var pageXY = ajax.GUI.getXY(el);
    if (pageXY === false) { return false; }
    var position = ajax.GUI.getStyle(el, 'position');
    if (!position || position == 'static') {
        el.style.position = 'absolute';     // first... it's relative
    }
    var delta = {
        x: parseInt( ajax.GUI.getStyle(el, 'left'), 10 ),
        y: parseInt( ajax.GUI.getStyle(el, 'top'), 10 )
    };
    if ( isNaN(delta.x) ) { delta.x = 0; }
    if ( isNaN(delta.y) ) { delta.y = 0; }
   
    if (x != null) {
        el.style.left = (x - pageXY.x + delta.x) + 'px';
    }
    if (y != null) {
        el.style.top = (y - pageXY.y + delta.y) + 'px';
    }   
    return true;
}

ajax.GUI.getSize = function(el) {
    var delta = {
        x: parseInt( ajax.GUI.getStyle(el, 'width'), 10 ),
        y: parseInt( ajax.GUI.getStyle(el, 'height'), 10 )
    };
        return delta;
}

ajax.GUI.setSize = function(el, x, y) {
   
    var pageXY = ajax.GUI.getXY(el);
    if (pageXY === false) { return false; }
    var position = ajax.GUI.getStyle(el, 'position');
    if (!position || position == 'static') {
        el.style.position = 'absolute';     // first... it's relative
    }
    var delta = {
        x: parseInt( ajax.GUI.getStyle(el, 'width'), 10 ),
        y: parseInt( ajax.GUI.getStyle(el, 'height'), 10 )
    };
    if ( isNaN(delta.x) ) { delta.x = 0; }
    if ( isNaN(delta.y) ) { delta.y = 0; }
   
    if (x != null) {
        el.style.width = x + 'px';
    }
    if (y != null) {
        el.style.height = y + 'px';
    }   
   
   
    return true;
}
ajax.Base64 = {  
 
     // private property  
     _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",  
 
     // public method for encoding  
     encode : function (input) {  
         var output = "";  
         var chr1, chr2, chr3, enc1, enc2, enc3, enc4;  
        var i = 0;  
  
         input = this._utf8_encode(input);  
  
         while (i < input.length) {  
  
             chr1 = input.charCodeAt(i++);  
             chr2 = input.charCodeAt(i++);  
             chr3 = input.charCodeAt(i++);  
  
             enc1 = chr1 >> 2;  
             enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);  
             enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);  
             enc4 = chr3 & 63;  
  
             if (isNaN(chr2)) {  
                enc3 = enc4 = 64;  
             } else if (isNaN(chr3)) {  
                 enc4 = 64;  
             }  
  
             output = output +  
             this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +  
             this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);  
  
         }  
  
         return output;  
     },  
  
     // public method for decoding  
     decode : function (input) {  
         var output = "";  
         var chr1, chr2, chr3;  
         var enc1, enc2, enc3, enc4;  
         var i = 0;  
  
         input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");  
  
         while (i < input.length) {  
  
             enc1 = this._keyStr.indexOf(input.charAt(i++));  
             enc2 = this._keyStr.indexOf(input.charAt(i++));  
             enc3 = this._keyStr.indexOf(input.charAt(i++));  
             enc4 = this._keyStr.indexOf(input.charAt(i++));  
  
             chr1 = (enc1 << 2) | (enc2 >> 4);  
             chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);  
            chr3 = ((enc3 & 3) << 6) | enc4;  
  
             output = output + String.fromCharCode(chr1);  
  
             if (enc3 != 64) {  
                 output = output + String.fromCharCode(chr2);  
             }  
             if (enc4 != 64) {  
                 output = output + String.fromCharCode(chr3);  
             }  
  
         }  
  
         //output = this._utf8_decode(output);  
  
         return output;  
  
     },    
     // private method for UTF-8 encoding  
     _utf8_encode : function (string) {  
         string = string.replace(/\r\n/g,"\n");  
         var utftext = "";  
  
         for (var n = 0; n < string.length; n++) {  
  
             var c = string.charCodeAt(n);  
  
             if (c < 128) {  
                 utftext += String.fromCharCode(c);  
             }  
             else if((c > 127) && (c < 2048)) {  
                 utftext += String.fromCharCode((c >> 6) | 192);  
                 utftext += String.fromCharCode((c & 63) | 128);  
             }  
             else {  
                 utftext += String.fromCharCode((c >> 12) | 224);  
                 utftext += String.fromCharCode(((c >> 6) & 63) | 128);  
                 utftext += String.fromCharCode((c & 63) | 128);  
             }  
  
         }  
  
         return utftext;  
     },  
  
     // private method for UTF-8 decoding  
     _utf8_decode : function (utftext) {  
         var string = "";  
         var i = 0;  
         var c = c1 = c2 = 0;  
  
         while ( i < utftext.length ) {  
  
             c = utftext.charCodeAt(i);  
  
             if (c < 128) {  
                 string += String.fromCharCode(c);  
                 i++;  
             }  
             else if((c > 191) && (c < 224)) {  
                 c2 = utftext.charCodeAt(i+1);  
                 string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));  
                 i += 2;  
             }  
             else {  
                 c2 = utftext.charCodeAt(i+1);  
                 c3 = utftext.charCodeAt(i+2);  
                 string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));  
                 i += 3;  
             }  
  
         }     
         return string;  
     }  
    
}

Ajax 기초

 

사용방법

           //한글 문서의 경우 뛰어 쓰기로 문제가 발생 Base64로 변환 루틴을 삽입한다.

            var sendText = ajax.Base64.encode(text);                   

            //서버로 보내는 방법

     params = "action=UpdateTextAreaPostit&uid="+uid+"&postitid="+this.postitId+"&textareacontent="+sendText;
     var send = new ajax.xhr.Request("./Servlet/PostitServlet", params, Js2postit.Postit.CallbackFunction , "POST");

CallbackFunction은 항상 설정해야 하며 특정 객체의 정보를 넣을수는 없다.

 

 

Js2postit.CallbackFunction = function(httpRequest){
    if(httpRequest.readyState == 4){
        if(httpRequest.status == 200){
            //결과 내용       
            xml = httpRequest.responseXML;
            //행동
            var action = xml.getElementsByTagName('action').item(0).firstChild.nodeValue;                                               
            //결과물
            var resultXML = xml.getElementsByTagName('result').item(0);                                               
            switch(action){               
                case 'GetFolderList' :               
                    Js2postit.GetFolder(resultXML);               
                    break;               
                default :                                                              
            }                                              
           
        }                       
    }
}

Base64 디코딩 자바 부분

String text_base = new String(decoder.decodeBuffer(text), "UTF-8");

 

 

파서 부분 예)

Js2postit.Shared.SharedSearchListParsing = function(resultXML){   
    /*
     * folderData ={              
        folderId : null ,
        folderTitle : null ,
        userId : null,
        shared : null               
    };
     * */
     
     
    var count = resultXML.getElementsByTagName('count').item(0).firstChild.nodeValue;       
    var Dictionary  = new dojo.collections.Dictionary();           
    for(num=1; num <= count ; num++){       
        shared = resultXML.childNodes.item(num);
        FolderData = Js2postit.Folder.FolderParsing(shared);       
        Dictionary.add(FolderData.folderId , FolderData);
    }       
    return Dictionary;
}

 

Event

  this.mouseDown = ajax.Event.bindAsListener(this.doMouseDown, this);
  this.mouseMove = ajax.Event.bindAsListener(this.doMouseMove, this);
  this.mouseUp = ajax.Event.bindAsListener(this.doMouseUp, this);

-특정 객체에 있는 메소드를 사용하기위해서 Bind 해주는 것입니다.

 

ajax.Event.addListener(this.pointElement, "mousedown", this.mouseDown);

바인드 마친 메소드를 Callback 메소드로 지정해서 사용합니다.

(이벤트가 나타날element , 이벤트 , 콜백 메소드)