+ -
当前位置:首页 → 问答吧 → 封装一个ajax方法,状态方法无法调用,求助各位

封装一个ajax方法,状态方法无法调用,求助各位

时间:2011-01-17

来源:互联网

JScript code
function AJAX_OBJ(url, callback, errorhandle, timer, retrial) {
            this.xmlHttp = null;
            this.num = 0;
            this.url = url;
            this.urlParameters = "";
            this.callback = callback;
            this.errorhandle = errorhandle; 
            this.timer = timer || 5000;
            this.timeout = -1;
            this.retrial = retrial || 1; 
            this.childnodes = null;  
        }

        AJAX_OBJ.prototype.createXMLHttpRequest = function() {
            var xmlh = null;
            xmlh = new XMLHttpRequest();
            return xmlh;
        }

        AJAX_OBJ.prototype.getInstance = function() {
            return this.createXMLHttpRequest();
        } 
        AJAX_OBJ.prototype.stateChanged = function() {
            
            iPanel.debug("this.xmlHttp.readyState ==" + this.xmlHttp.readyState);
            if (this.xmlHttp.readyState == 4) {
                if (this.xmlHttp.status == 200) {
                    this.callback(this.xmlHttp);
                }
                else {//error handling
                    this.num++;
                    this.errorhandle(this.xmlHttp.status);
                    if (this.retrial != -1 && this.num < this.retrial) {
                        var _self = this;
                        clearTimeout(this.timeout);
                        this.timeout = setTimeout(function() { _self.requestData(); }, this.timer);
                    }
                    else if (this.retrial == -1) {
                    _self = this;
                        clearTimeout(this.timeout);
                        this.timeout = setTimeout(function() { _self.requestData(); }, this.timer);
                    }
                }
            }
        } 
        AJAX_OBJ.prototype.requestData = function() {
            this.xmlHttp = this.getInstance();
            var request_url = this.url + this.urlParameters;
            var _self = this;
            this.xmlHttp.onreadystatechange = function() {
                alert(_self.stateChanged());
                _self.stateChanged(); //这里的self对象为未定义,不知道是怎么回事


            };

            this.xmlHttp.open("GET", request_url, true); 
            this.xmlHttp.send(null);
        }

作者: zbdess150   发布时间: 2011-01-17

创建对象有问题,IE6-浏览器无法创建XMLHttpRequest对象

JScript code
AJAX_OBJ.prototype.createXMLHttpRequest = function() {
            var xmlh = null;
if(window.ActiveXObject)xmlh=new ActiveXObject("microsft.xmlhttp");
else            xmlh = new XMLHttpRequest();
            return xmlh;
        }



我用你的类库没发现有什么问题。
JScript code
this.xmlHttp.onreadystatechange = function() {
                alert(_self.stateChanged());//=========应该这里是undefined,因为你的函数没有返回值
                _self.stateChanged(); //这里的self对象为未定义,不知道是怎么回事


            };

作者: showbo   发布时间: 2011-01-19