Javascript 类中的 XMLHttpRequest

Sae*_*ari 3 javascript ajax jquery

我已经定义了一个类,我正在尝试使用获取一个 HTML 文件XMLHttpRequest并将响应分配给类中的变量,但它不会改变。

function UIHandler(){
    this.notificatoin = 0;
    this.msgBoxMe = 1;
    this.msgBoxThem = 2;
    this.getMsgBox(1);
    this.getMsgBox(2);
}

UIHandler.prototype.getMsgBox = function(me){
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){//here we have the template in xhr.responseText
            this.msgBoxMe = xhr.responseText;
        }
    };
    switch(me){
        case 1:
            xhr.open("GET" , "chat/views/me.html" , true);
            break;
        case 2:
            xhr.open("GET" , "chat/views/them.html" , true);
            break;
    }
    xhr.send();
};
Run Code Online (Sandbox Code Playgroud)

我将onreadystatechange事件处理程序中的响应分配给this.msgBoxMe变量,但它的值仍然为 1。

Mar*_*fer 5

回调xhr.onreadystatechange中的this变量不指向该对象。

一种解决方法是定义一个额外的变量(例如,其保持该物体在下面的示例):

function UIHandler() {
    this.notificatoin = 0;
    this.msgBoxMe = 1;
    this.msgBoxThem = 2;
    this.getMsgBox(1);
    this.getMsgBox(2);
}

UIHandler.prototype.getMsgBox = function(me){
    var instance = this;   // points to object

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
         if(xhr.readyState == 4){ //here we have the template in xhr.responseText
              instance.msgBoxMe = xhr.responseText;
         }
    };
    switch(me){
         case 1:
              xhr.open("GET" , "chat/views/me.html" , true);
              break;
         case 2:
              xhr.open("GET" , "chat/views/them.html" , true);
              break;
    }
    xhr.send();
};
Run Code Online (Sandbox Code Playgroud)