AJAX对象IE 8错误

时间:2011-03-30 17:56:22

标签: javascript ajax internet-explorer

使用下面的代码,我收到错误:

消息:未实现。 行:this.xmlHttpRequestObject.onreadystatechange = onreadystatechange;

ajax.js

function Ajax(url, method, onreadystatechange, asynchronous) {
    this.xmlHttpRequestObject = new XMLHttpRequest();
    this.method = method;
    this.url = url;
    this.asynchronous = asynchronous === undefined ? true : asynchronous;
    this.xmlHttpRequestObject.onreadystatechange = onreadystatechange;
}

Ajax.prototype.send = function () {
    this.xmlHttpRequestObject.open(this.method, this.url, this.asynchronous);
    this.xmlHttpRequestObject.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    this.xmlHttpRequestObject.send();

    return this;
};

Ajax.prototype.onreadystatechange = function (onreadystatechange) {
    this.xmlHttpRequestObject.onreadystatechange = onreadystatechange;

    return this;
};

Ajax.prototype.onloadstart = function (onloadstart) {
    this.xmlHttpRequestObject.onloadstart = onloadstart;

    return this;
};

Ajax.prototype.onload = function (onload) {
    this.xmlHttpRequestObject.onload = onload;

    return this;
};

scripts.js中

function loadPage(page) {
    var ajax = new Ajax(page, 'GET');

    ajax.onloadstart(function () {
        var div = document.createElement('div'),
            p = document.createElement('p'),
            img = document.createElement('img'),
            section = document.querySelector('section');

        removeChildrenElements(section);
        section.style.minHeight = '230px';

        div.setAttribute('id', 'loading');

        img.setAttribute('src', 'media/images/loading.gif');
        img.setAttribute('alt', 'Carregando');

        p.appendChild(document.createTextNode('Carregando. Por favor, aguarde ...'));

        div.appendChild(p);
        div.appendChild(img);

        document.querySelector('section').appendChild(div);
    });

    ajax.onreadystatechange(function (event) {
        if (this.readyState === 4 && this.status === 200) {
            document.querySelector('section').innerHTML = this.responseText;
        } else if (this.status === 404) {
            this.abort();
            document.location = 'http://www.mydomain.com.br/404';
        }
    });

    ajax.send();
}

此脚本适用于Firefox 4,Google Chrome和Opera。 谢谢。

1 个答案:

答案 0 :(得分:0)

可能与窗口/文档对象发生冲突。尝试将代码更改为

Ajax.prototype.onreadystatechange = function (readystatechange) {
    this.xmlHttpRequestObject.onreadystatechange = readystatechange;
    return this;
};