基於對象的JavaScript實現無重新整理頁面發送和擷取資料Ajax.js

來源:互聯網
上載者:User

     大家都知道,JavaScript是基於對象的語言,它有物件導向的部分特徵,所以我們能用對象的思想來寫一些頁用戶端需要實現的一些功能。

Ajax.js是一個Javascript通過xmlHttpRequest對象擷取後台資料的一個指令碼架構,可以很方面的擷取後台伺服器端執行代碼返回的文本或XML格式的資料。當然.net下的UpdatePanel控制項可以很好的實現頁面資料不重新整理的問題,但是運用得不恰當的話會影響傳輸上的效率。然而Ajax.js中的xmlHttpRequest對象是建立一個非同步Http請求,向伺服器端擷取資料,傳輸速度對於效能影響甚小。

下面是一個典型的運用Javascript物件導向的思想來實現的這種架構,從自己的實際項目中抽取出來的。便於以後總結。

 

// JScript 檔案
function StringBuilder()
{
    this._content = new Array();
    if( typeof StringBuilder._init  == "undefined" )
    {
        StringBuilder.prototype.Append  = function(str)
        {
            this._content.push( str );
        }
        StringBuilder.prototype.ToString = function()
        {
            return this._content.join("");
        }
        StringBuilder._init = true;
    }
}
function Ajax()
{
    this._xmlHttp = (function()
                    {
                        try
                        {
                            if( window.ActiveXObject )
                            {
                                var arrSignature = ["MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0",
                                                    "MSXML2.XMLHTTP.2.0","Microsoft.XMLHTTP"];
                                for( var i = 0; i < arrSignature.length; i++ )
                                {
                                    try{
                                            return  new ActiveXObject(arrSignature[i]);
                                       }
                                    catch( exception )
                                    {
                                    }
                                }
                            }
                            else
                            {
                                return new XMLHttpRequest();
                            }
                        }
                        catch(exception)
                        {
                            throw new Error("Your browser doesn't support XMLHttpRequest object!");
                        }
                    })();
     this._params = new StringBuilder();
     if( typeof Ajax._init == "undefined")
     {
        Ajax.prototype.Get = function(url, oFunction)
        {
            var oXMLHttp = this._xmlHttp;
            this._xmlHttp.open("get",url+this.GetParams(),true);
            this._xmlHttp.onreadystatechange = function()
                                                        { 
                                                            if( oXMLHttp.readyState == 4 )
                                                            oFunction(oXMLHttp.responseText,oXMLHttp.responseXml);
                                                        };
            this._xmlHttp.setRequestHeader("Cache-Control","no-cache"); 
            this._xmlHttp.send(null);
        }
        Ajax.prototype.Post = function(url, oFunction)
        {
            var oXMLHttp = this._xmlHttp;
            this._xmlHttp.open("post",url,true);
            this._xmlHttp.onreadystatechange = function()
                                                        {
                                                            if(oXMLHttp.readyState==4 )
                                                                oFunction(oXMLHttp.responseText,oXMLHttp.responseXml);
                                                        }
            this._xmlHttp.setRequestHeader("Cache-Control","no-cache");                                             
            this._xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            this._xmlHttp.send(this.GetParams().substring(1));
        }
        Ajax.prototype.AddParams = function( name, value )
        {   if( this._params.ToString().indexOf("?")== -1 )
            {
                this._params.Append("?");
            }
            else
            {
                this._params.Append("&");
            }
            this._params.Append( encodeURIComponent(name) );
            this._params.Append( "=" );
            this._params.Append( encodeURIComponent(value));
        }
        Ajax.prototype.GetParams = function()
        {
            return this._params.ToString() +"&rand="+ Math.random();
        }
        Ajax._init = true;
     }
}

 

Post方式的調用方式如下:(Get方式也同理)

var ajax=new Ajax();
ajax.AddParams("Name","CharlesChen");
ajax.AddParams("Sex","男");
ajax.Post("test.aspx",function()
{
    HandlesMethod(arguments[0],arguments[1])
});

其中HandlesMethod是一個回呼函數接受兩一個參數,一個是返回的文字格式設定的資料,另一個是返回的是XML格式的資料。這樣我們就可以對返回回來的資料進行處理了。這樣實現起來感覺上就像後台代碼那樣有物件導向的含義,理解起來也更簡單,實現起來也更容易。希望這篇文章對朋友們有協助。

ps,另外可以把上面的那Ajax.js放到項目中去運用,減少開發量,增加工作效率。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.