Skip to content Skip to sidebar Skip to footer

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(){ thi

Solution 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:

functionUIHandler() {
    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 objectvar xhr = newXMLHttpRequest();
    xhr.onreadystatechange = function(){
         if(xhr.readyState == 4){ //here we have the template in xhr.responseText
              instance.msgBoxMe = xhr.responseText;
         }
    };
    switch(me){
         case1:
              xhr.open("GET" , "chat/views/me.html" , true);
              break;
         case2:
              xhr.open("GET" , "chat/views/them.html" , true);
              break;
    }
    xhr.send();
};

Post a Comment for "Xmlhttprequest In Javascript Class"