js 精簡版Ajax功能

來源:互聯網
上載者:User

版本:version 1.0

作者:lz_wu

時間:2011/06/28

調用方式:

ajaxHandler.Ajax({

                url: "webtest.aspx",

                type: "get",

                data: { name: "joy" },

                dataType: "json",

                success: function (result) {

                    alert(result.name);

                },

                error: function (e, status) {

                    alert(e.responseText);

                    //var result = eval("(" + e.responseText + ")");

                    //alert(e.exception.message);

                }

            });

願望:希望有人看到並使用後,可以更加的完善這個功能,在些感謝

代碼內容如下:

var ajaxHandler = {

    defaultOptions: {

        url: "", //url地址

        type: "get", //訪問方式

        async: true, //同步還是異步調用

        timeout: -1, //超時設置

        cache: true, //緩存設置

        data: {}, //參數傳遞

        dataType: "",//返回類型

        success: function () { }, //成功時搪行的函數

        error: function () { } //失敗時執行的函數

    },

    tiemOutSet: null,//超時

    xmlHttp: function () {//創建XMLHttpRequest對象

        var xmlhtp = null;

        if (window.XMLHttpRequest)

            xmlhtp = new XMLHttpRequest();

        else {

            if (window.ActiveXObject) {

                xmlhtp = new ActiveXObject("Microsoft.XMLHTTP") || new ActiveXObject("Msxml2.XMLHTTP");

            }

        }

        return xmlhtp;

    },

    extend: function (arg1, arg2) {//重載默認設置

        for (var n in arg2) {

            if (arg1[n] != undefined)

                arg2[n] = arg1[n];

        }

    },

    Ajax: function (obj) {

        var xmlhttpRequest = this.xmlHttp();

        if (xmlhttpRequest == null) { alert("you bowerse is not support Ajax!"); return; }

        this.extend(obj, this.defaultOptions);

        var current = this;

        xmlhttpRequest.onreadystatechange = function () {

            current.AjaxSuccess(xmlhttpRequest);

        }

        xmlhttpRequest.open(this.defaultOptions.type, this.getAjaxUrl(), this.defaultOptions.async);

        this.setHeaderInfo(xmlhttpRequest); //設置頭部資訊

        xmlhttpRequest.send(null); //發送請求

        this.timeoutHandler(this.stopTimeOut, xmlhttpRequest); //超時處理

    },

    setHeaderInfo: function (xmlhttpRequest) {//默認設置頭部資訊

        if (this.defaultOptions.dataType == "" && this.defaultOptions.type.toLowerCase() == "post") {

            xmlhttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        }

        if (this.defaultOptions.dataType != "") {

            switch (this.defaultOptions.dataType.toLowerCase())//返回類型

            {

                case "xml": xmlhttpRequest.setRequestHeader("Content-Type", "text/xml;charset=utf-8"); break;

                case "html": xmlhttpRequest.setRequestHeader("Content-Type", "text/html;charset=utf-8"); break;

                case "json": break;

                case "script": break;

                default: xmlhttpRequest.setRequestHeader("Content-Type", "text/xml;charset=utf-8");

                break;

            }

        }

    },

    getAjaxUrl: function () {//url的處理

        var url = "";

        var arr = new Array();

        for (var name in this.defaultOptions.data)

            arr.push(name + "=" + this.defaultOptions.data[name]);

        if (arr.length != 0) url = this.defaultOptions.url + "?" + arr.join("&");

        else url = this.defaultOptions.url;

        if (this.defaultOptions.cache == false) {//表示不緩存

            if (url.indexOf("?") == -1)

                url += "?timeSpan=" + new Date().getTime();

            else

                url += "&timeSpan=" + new Date().getTime();

        }

        return url;

    },

    timeoutHandler: function (callback, xmlhttpRequest) {

        if (this.defaultOptions.timeout != -1) {

            //var _cb = function () {}

            this.tiemOutSet = setTimeout(function () {

                callback.apply(null, xmlhttpRequest);

            }, this.defaultOptions.timeout);

        }

    },

    stopTimeOut: function (xmlhttpRequest) {//表示超時處理的函數

        if (this.tiemOutSet != null) {

            if (xmlhttpRequest) xmlhttpRequest.abort(); //阻止提交

            clearTimeout(this.tiemOutSet); //清除超時時間

            this.tiemOutSet = null;

        }

    },

    AjaxSuccess: function (xmlhttpRequest) {//成功時執行的函數

        if (xmlhttpRequest) {

            switch (xmlhttpRequest.readyState) {

                case 0: break; //已經建立一個XMLHttpRequest對象,但是還沒有初始化。

                case 1: break; //已經調用了XMLHttpRequest open()方法並且XMLHttpRequest已經準備好把一個請求發送到伺服器。

                case 2: break; //已經通過send()方法把一個請求發送到伺服器端,但是還沒有收到一個響應。

                case 3: break; //已經接收到HTTP回應標頭部資訊,但是訊息體部分還沒有完全接收結束。

                case 4: //已載入"狀態;此時,響應已經被完全接收。

                    if (xmlhttpRequest.status == 200) {//表示成功

                        this.defaultOptions.success(this.returnType(xmlhttpRequest));

                    }

                    else

                        this.defaultOptions.error(xmlhttpRequest, xmlhttpRequest.status);

                    break

                default: break;

            }

 

        }

    },

    returnType: function (xmlhttpRequest) {//返回類型的處理

        var content;

        if (this.defaultOptions.dataType != "") {

            switch (this.defaultOptions.dataType.toLowerCase()) {

                case "xml": content = xmlhttpRequest.responseXML; break;

                case "html": content = xmlhttpRequest.responseText; break;

                case "json": content = eval('(' + xmlhttpRequest.responseText + ')'); break;

                default: content = xmlhttpRequest.responseText; break;

            }

        }

        else

            content = xmlhttpRequest.responseText;

        return content;

    }

};

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.