티스토리 뷰

음 이참에 ajax와 json으로 사이트를 구현하다가..
만든 javascript 입니다. 혼자서 구현하다 보니..
단점도 있고 해서.. 같이 해 같으면 하는 바램에서 올려봅니다.

이 스크립트는?
비동기식과 동기식을 모두 지원합니다.
함께 하실분은 저에게 이메일을 주신다면 감사.~! ^^


var debugEngine = false;

function Engine()
{
    this.xmlhttp = false;
    this.type        = null;
    this.src            = null;
    this.param    = null;
    this.exec        = null;
    this.ifrcnt        = 0;
    this.iswait    = false; //동시에 두개가 호출되었다면

    /*
     * AJAX 기본 클래스 함수
     * type : GET, AGET, POST, IPOST, IGET
     *        GET : 동기식 GET                (비추천)
            AGET : 비동기식 GET형        (추천)
            POST : 비동기식 POST형        (추천)
            IPOST : 동기식 IFRAME 형    (비추천)
            IGET : 동기식 GET형            (비추천)
     * src : URL
     * param : POST방식에서 사용됨
     * exec : 리턴할 함수명
     */
    this.execute = function(type, src, param, exec)
    {
        //alert('type : '+type+' src : '+ src+' param : '+param + 'exec : '+ exec);
        this.type        = type;
        this.src            = src;
        this.param    = param;
        this.exec        = exec;
        this.getXmlHttpRequest();
        this.iswait    = true;        

        try    
        {           
            return this._execute();
        }
        catch (e)
        {           
            this.errorHandle('데이터에 접근할 수 없습니다.');            
        }       
    }


    this.getXmlHttpRequest = function()
    {           
        if(this.iswait == true)
        {
            setTimeout("engine.getXmlHttpRequest();",200);
            return;
        }
        else
        {           
            if(window.XMLHttpRequest)            
            {
                this.xmlhttp = new XMLHttpRequest();
            }
            else if (window.ActiveXObject && !(navigator.userAgent.indexOf('Mac') >= 0 && navigator.userAgent.indexOf("MSIE") >= 0))
            {
                this.xmlhttp = this._ActiveXObject(["Microsoft.XMLHTTP","Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP"]);
            }
        }
    }


    this._ActiveXObject = function (axarray)
    {
        var returnValue;
       
        for (var i = 0; i < axarray.length; i++)
        {
            try
            {               
                returnValue = new ActiveXObject(axarray[i]);
                break;
            }
            catch (ex)
            {
            }
        }

        return returnValue;
    }



    // GET, AGET, POST 형식
    this._execute = function()
    {           

        if(this.type == 'GET' || this.type == 'AGET')
        {
            this.xmlhttp.open("GET",this.src, this.type == 'GET' ? false : true);
        }
        else if(this.type == 'POST')
        {
            this.xmlhttp.open("POST",this.src, true);    
        }
        else if(this.type == 'IPOST' || this.type == 'IGET')
        {           
            this._executeIFR();
            return;
        }       


        this.xmlhttp.setRequestHeader("Content-type:", this.type == 'POST' ? "application/x-www-form-urlencoded" : "text/xml");
        this.xmlhttp.setRequestHeader("Cache-Control:", "no-cache");
        this.xmlhttp.setRequestHeader("Pragma:", "no-cache");
        this.xmlhttp.setRequestHeader("Referer:", this.src);
       
        if(this.type == 'AGET' || this.type == 'POST') // 비동기식 GET, POST
        {           
            this.xmlhttp.onreadystatechange = function()
            {               
                if(engine.xmlhttp.readyState == 4)
                {                    
                    if(engine.xmlhttp.status == 200)
                    {                           
                        var result = engine.xmlhttp.responseText;                        
                        engine.debugPrint(result);                        
                        if(engine.exec) eval(engine.exec +'(result);');
                        engine.iswait = false;
                    }
                }
            }
           
            if(this.type == 'AGET')                this.xmlhttp.send(null);
            else if(this.type == 'POST')        this.xmlhttp.send("info="+this.param);
        }
       
        else if(this.type == 'GET') // 동기식 GET
        {
            this.xmlhttp.send(null);

            if (this.xmlhttp.status == 200)
            {   
                this.debugPrint();
                this.iswait = false;
                return ( this.xmlhttp.responseText );
            }
        }
    }


    // IFRAME 형식의 POST //
    this._executeIFR = function()
    {
        var idname = 'ul-ifr-no'+this.ifrcnt
        var xmlDiv = null;        var xmlIfr = null;    var xmlForm = null; var formInput = null;

        xmlDiv = document.createElement('div');
        if(debugEngine)
            xmlDiv.innerHTML = "<iframe frameborder='0' width='800' height='200' id='" + idname + "' name='" + idname + "'></iframe>";
        else
            xmlDiv.innerHTML = "<iframe frameborder='0' width='0' height='0' id='" + idname + "' name='" + idname + "'></iframe>";
        document.body.appendChild(xmlDiv);
   
xmlIfr = document.getElementById(idname);
xmlIfr.setAttribute('style', 'width:0px; height:0px; border:0px;');        
       
        if(this.type == 'IPOST')
        {           
            xmlForm = document.createElement('form');
            xmlForm.setAttribute('id', 'ul-form');
            xmlForm.setAttribute('action', this.src);
            xmlForm.setAttribute('target', idname);
            xmlForm.target = idname;
            xmlForm.setAttribute('method', 'post');

            formInput = document.createElement('input');
            formInput.setAttribute('type', 'hidden');
            formInput.setAttribute('name', 'info');
            formInput.setAttribute('value', this.param);
            xmlForm.appendChild(formInput);

            document.body.appendChild(xmlForm);
            xmlForm.submit();
        }
        else if(this.type == 'IGET')
        {
            xmlIfr.src = this.src;    
            document.body.appendChild(xmlIfr);
        }
        this.ifrcnt++;
    }


    // 에러핸들러
    this.errorHandle = function(code)
    {
        alert(code);
    }


    // Debug //
    this.debugPrint = function(value)
    {
        if(debugEngine == 'div')
        {
        }
        else if(debugEngine == 'alert')
            alert(value);
        else
            return;
    }

}

var engine = new Engine();





======================================================================================

덧글 :

======================================================================================

와~~ 좋은 소스 잘 사용하겠습니다.
하지만 오류가있군요.

 this.xmlhttp.setRequestHeader("Content-type:", this.type == 'POST' ? "application/x-www-form-urlencoded" : "text/xml");
this.xmlhttp.setRequestHeader("Cache-Control:", "no-cache");
this.xmlhttp.setRequestHeader("Pragma:", "no-cache");
this.xmlhttp.setRequestHeader("Referer:", this.src);
이걸

this.xmlhttp.setRequestHeader("Content-type", this.type == 'POST' ? "application/x-www-form-urlencoded" : "text/xml");
        this.xmlhttp.setRequestHeader("Cache-Control", "no-cache");
        this.xmlhttp.setRequestHeader("Pragma", "no-cache");
        this.xmlhttp.setRequestHeader("Referer", this.src);
이렇게 해야 잘 됩니다.


======================================================================================

덧글2:

======================================================================================

http://script.aculo.us/ 강추

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크