大K自己封裝的AJAX

2 Comments Posted by jeffery on 2010-06-29, under javascript

全能的K神啊,請賜予我力量吧~

大K自己封裝的AJAX,僅以此帖作為收藏,以表達我對大k那有如濤濤江水,連綿不絕的景仰之情!

(function () {
            var kinogam;
            if (!window.kinogam)
                kinogam = window.kinogam = new Object();
            else
                kinogam = window.kinogam;

            kinogam.ajax = function (s) {
                var x = new kinogam.ajaxHandler();
                x.setMember(s);

                x.xmlHttp.onreadystatechange = function () {
                    if (x.xmlHttp.readyState == 4 && ((x.xmlHttp.status >= 200 && x.xmlHttp.status < 300) ||
                     x.xmlHttp.status == 304 || x.xmlHttp.status == 1223)) {
                        if (x.success != null)
                            x.success.call(x,x.xmlHttp.responseText);
                    }
                    else if (x.xmlHttp.readyState == 4) {
                        if (x.error != null)
                            x.error.call(x,x.xmlHttp.responseText);
                    }
                }
                x.xmlHttp.open(x.type, x.url, x.async);
                try {
                    x.xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    x.xmlHttp.send(kinogam.ajax.json2url(x.data));
                }
                catch (e) {
                }
            }

            kinogam.ajaxHandler = function () {
                this.url = "";
                this.type = "POST";
                this.data = null;
                this.async = true;
                this.success = null;
                this.error = null;
                this.xmlHttp = kinogam.ajax.getXmlHttpRequest();
            }
            kinogam.ajaxHandler.prototype.setMember = function (s) {
                if (s != null) {
                    for (var i in s) {
                        this[i] = s[i];
                    }
                }
            }
            kinogam.ajax.getXmlHttpRequest = function () {
                return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();

            }
            kinogam.ajax.json2url = function (json) {
                var url = "";
                for (var i in json) {
                    url += "&" + encodeURIComponent(i) + "=" + encodeURIComponent(json[i]);
                }
                return url.replace(/^&/, "");
            }
        })();

        kinogam.ajax({
            url: "handler.ashx",
            data: { b: "kkkyyy" },
            success: function (html) {
                alert(html);
            }

        });