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:
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();
};
Post a Comment for "XMLHttpRequest In Javascript Class"