Объектно-ориентированный JavaScript - класс AJAX - PullRequest
0 голосов
/ 28 ноября 2011

Работа над классом AJAX. Вот код:

function AjaxRequest(params) {
    if (params) {
        this.params = params;
        this.type = "POST";
        this.url = "login.ajax.php";
        this.contentType = "application/x-www-form-urlencoded";
        this.contentLength = params.length;
    }
}

AjaxRequest.prototype.createXmlHttpObject = function() {
    try {
        this.xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        try {
            this.xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
        }
        catch (e) {}
    }

    if (!this.xmlHttp) {
        alert("Error creating XMLHttpRequestObject");
    }
}

AjaxRequest.prototype.process = function() {
    try {
        if (this.xmlHttp) {
            this.xmlHttp.onreadystatechange = this.handleRequestStateChange();
            this.xmlHttp.open(this.type, this.url, true);
            this.xmlHttp.setRequestHeader("Content-Type", this.contentType);
            this.xmlHttp.setRequestHeader("Content-Length", this.contentLength);
            this.xmlHttp.send(this.params);
            }
        }
        catch (e) {
            document.getElementById("loading").innerHTML = "";
            alert("Unable to connect to server");
        }
    }

AjaxRequest.prototype.handleRequestStateChange = function() {
    try {
        if (this.xmlHttp.readyState == 4 && this.xmlHttp.status == 200) {
            this.handleServerResponse();
        }
    }
    catch (e) {
        alert(this.xmlHttp.statusText);
    }
}

AjaxRequest.prototype.handleServerResponse = function() {
    try {
        document.getElementById("loading").innerHTML = this.xmlHttp.responseText;
    }
    catch (e) {
        alert("Error reading server response");
    }
}

Который тогда явно создается так:

var ajaxRequest = new AjaxRequest(params);
ajaxRequest.createXmlHttpObject();
ajaxRequest.process();

У меня проблема с методом handleRequestStateChange, так как он обрабатывает xmlHttp.onreadystatechange. Обычно, когда вы определяете функцию для onreadystatechange, вы не включаете круглые скобки при ее вызове, например xmlHttp.onreadystatechange = handleRequestStateChange; Но поскольку я пытаюсь сохранить handleRequestStateChange() в области действия класса, у меня возникают проблемы с onreadystatechange. Функция действительно вызывается, но, похоже, застревает на readyState, равном 0.

Буду признателен за любую помощь или понимание. Пожалуйста, дайте мне знать, если необходимо указать более подробную информацию или мне что-то неясно.

1 Ответ

3 голосов
/ 28 ноября 2011
AjaxRequest.prototype.handleRequestStateChange = function() {
    var self = this;

    return function() {
        try {
            if (self.xmlHttp.readyState == 4 && self.xmlHttp.status == 200) {
                self.handleServerResponse();
            }
        }
        catch (e) {
            alert(self.xmlHttp.statusText);
        } 
    };
}

Теперь, когда вы выполните this.xmlHttp.onreadystatechange = this.handleRequestStateChange();, она вернет связанную функцию, которая перехватила правильную ссылку this на self, которая используется внутри фактической функции onreadystatechange.

...