DIV CSS 佈局教程網

AJAX 簡歷系統附完整 JS 封裝文件
編輯:AJAX基礎知識     

本文分享一份 AJAX 簡歷系統所使用的核心 JS 文件。這份代碼把 XMLHttpRequest 對象的創建、請求發送、狀態監控與回調處理等環節都做了細緻的封裝,是一個學習 Ajax 面向對象封裝思路的好例子。

/**********************************************
 * @author         skyz
 * @function       javascript client ajax dealwith
 * @datetime       2006-3-20
 **********************************************
 * Function: Create a httpRequest object
 **********************************************/
function HttpRequest(){
    this._httpRequest=null;      //HttpRequest request object
    this._callBack=null;         //Call back function
    this._domResult=true;        //Result if dom object or text string
    this._requestData=null;      //Request data
    this._requestResult=null;    //HttpRequest result
    this._stateString=null;      //Current request state string
    this._error=false;           //Current if have error
    this._callBackPara=null;     //Current callback function parama

    //internal method for get HttpRequestObject
    this.init=function(){
        //Judge if Not IE
        if(window.XMLHttpRequest){
            this._httpRequest=new XMLHttpRequest();
            //Set request mime is text/xml
            if(this._httpRequest.overrideMimeType){
                this._httpRequest.overrideMimeType('text/xml');
            }
        }else if(window.ActiveXObject){
            try{
                this._httpRequest=new ActiveXObject("Msxml2.XMLHTTP");
            }catch(ex){
                try{
                    this._httpRequest=new ActiveXObject("Microsoft.XMLHTTP");
                }catch(ex){
                    this._setMessage(ex,true);
                    return;
                }
            }
        }
        //Judge HttpRequest object create successful
        if(!this._httpRequest){
            this._setMessage("XMLHttpRequest 對象創建失敗!請重試......",true);
            return;
        }
    }

    //Set the request header
    this.doSetRequestHeader=function(namePar,valuePar){
        if(this._error){ return; }
        this._httpRequest.setRequestHeader(namePar,valuePar);
    }

    //Set the request data
    this.doSetRequestData=function(dataPar){
        if(this._error){ return; }
        this._requestData=dataPar;
    }

    //get RequestHttp Object
    this._getRequestObj=function(){
        if(this._error){ return; }
        return this._httpRequest;
    }

    //Set Callback function para
    this.doSetCallBack=function(callBack,paraData){
        this._callBack=(callBack)?callBack:null;
        this._callBackPara=(paraData)?paraData:null;
    };

    //Get current stateString
    this.doGetState=function(){
        return this._stateString;
    }

    //get current Error
    this.doGetError=function(){
        return this._error;
    }

    this.doCallBack=function(){
        this._callBack(this._requestResult,this._callBackPara);
    }

    //Send the request
    //urlPar: request's url path
    //[methodPar]: request's method
    //[domPar]: request's result is dom or string
    this.doSendResuest=function(urlPar,methodPar,obj,domPar,asyPar){
        if(obj._error){ return; }
        methodPar=((methodPar)?methodPar:"GET");
        asyPar=((asyPar)?asyPar:true);
        this._domResult=(domPar)?domPar:obj._domResult;
        try{
            var a=this._getRequestObj();
            a.onreadystatechange=function(){
                if(obj._error){ return; }
                var readyStateTmp=a.readyState;
                if(readyStateTmp==0){
                    obj._setMessage("未初始化!");
                }else if(readyStateTmp==1){
                    obj._setMessage("正在讀取中......");
                }else if(readyStateTmp==2){
                    obj._setMessage("已經讀取過!");
                }else if(readyStateTmp==3){
                    obj._setMessage("正在逐個切換......");
                }else if(readyStateTmp==4){
                    var statusTmp=a.status;
                    if(statusTmp==404){
                        obj._setMessage("未找到請求頁面!",true);
                    }else if(window.location.href.indexOf("http")==-1 || statusTmp==200){
                        obj._setMessage("完成!");
                        if(this._domResult && window.XMLHttpRequest){
                            obj._requestResult=a.responseXml;
                        }else{
                            obj._requestResult=a.responseText;
                        }
                        if(obj._callBack){
                            obj.doCallBack();
                        }
                    }else{
                        obj._setMessage("未知錯誤!");
                    }
                }else{
                    obj._setMessage("未知錯誤!");
                }
            }
            a.open(methodPar,urlPar,asyPar);
            a.send(obj._requestData);
        }catch(ex){
            obj._setMessage(ex,true);
        }
    }

    //Deal exception error
    //exPar: error string
    this._setMessage=function(exPar,mark){
        this._stateString=exPar.toString();
        this._error=(mark)?mark:false;
    }
}

封裝設計亮點

這個 HttpRequest 類的設計相當值得學習:它把請求對象、回調函數、請求數據、狀態字符串、錯誤標記等都封裝成了私有成員變量,並通過一系列 doSetXXX、doGetXXX 方法對外提供操作接口。

其中 doSendResuest 方法對 readyState 的 0 到 4 五種狀態都做了細緻的中文提示,並區分了 404 錯誤、成功、未知錯誤等多種情況,最後根據配置決定返回 DOM 對象還是文本字符串,並觸發回調。這種把狀態監控、錯誤處理、回調機制融為一體的封裝思路,對於構建可維護的 Ajax 應用很有借鑒意義。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved