js类 - 第一个ajax对象,无法获得结果

时间:2013-03-17 17:03:48

标签: javascript ajax class

这是我在js的第一堂课,我需要帮助才能得到严谨的结果

function ajaxObject (url, data, type) {
this.url = url;
this.data = 'data='+JSON.stringify(data) || null;
this.type = type ? type : 'json';
this.result = null;
var self = this;

this.create = function () {
    //se il browser ? firefox
    if (window.XMLHttpRequest) {
        //istanzio un nuovo oggetto XMLHttpRequest
        this.oHttp = new XMLHttpRequest();
        if (this.oHttp.overrideMimeType) {
            this.oHttp.overrideMimeType('text/xml');
        }
    //se il browser ? IE    
    } else if (window.ActiveXObject) {
        try {
            this.oHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                this.oHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
            }
        }
    }
};

this.process = function () {
    if (this.oHttp) {
        this.oHttp.open("POST", this.url, true);
        this.oHttp.onreadystatechange = this.manage;

        if (this.oHttp.overrideMimeType) {
            this.oHttp.overrideMimeType("application/json");
        }
        this.oHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        this.oHttp.setRequestHeader("Content-length", this.data.length);
        this.oHttp.send(this.data);
    }
};

this.manage = function () {
    // alert(self.oHttp.readyState + ' - ' + self.oHttp.responseText);
    if (this.readyState === 4 && this.status === 200) {
        // here this.responseText is correctly populated
        self.result = this.responseText;
        } else {
        self.requestFailed('message', this);
        return;
    }
};

this.getResult = function () {
    switch (this.type) {
        case 'text':
            return this.result;
            break;
        case 'json':
            return $.parseJSON(this.result);
            break;
    }
};

this.requestFailed = function (id, request) {
    if (document.getElementById) {
        sys.clearContent(id);
        document.getElementById(id).innerHTML = 'The XMLHttpRequest failed, STATUS: ' + request.status;
    }
};

}

我尝试以这种方式获得结果:

var ao = new ajaxObject('output.php', {mutator: "orders", get: "orders"});
ao.create();
ao.process();
var r = ao.getResult();
alert(r);

但是我无法得到我预期的结果..所有服务器端都完美无缺,但我的结果变量总是“空”..我想有一些我想念的东西,如果有人能帮助我请:)

0 个答案:

没有答案