简体   繁体   中英

XMLHttpRequest in Javascript Class

I have defined a class and I am trying to fetch a HTML file using XMLHttpRequest and assign the response to the variable in class but it won't change.

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();
};

I assign the response in the onreadystatechange event handler to the this.msgBoxMe variable but it still has the value 1.

The this variable in your callback xhr.onreadystatechange doesn't point to the object.

A workaround is to define an additional variable ( instance in the following example) that holds the object:

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();
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM