Javascript类中的XMLHttpRequest [英] XMLHttpRequest in Javascript Class
问题描述
我已经定义了一个类,并且尝试使用XMLHttpRequest
提取HTML文件并将响应分配给该类中的变量,但是它不会改变.
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();
};
我将onreadystatechange
事件处理程序中的响应分配给this.msgBoxMe
变量,但它仍然具有值1.
回调 xhr.onreadystatechange 中的 this 变量未指向该对象.>
一种解决方法是定义一个包含对象的附加变量(在下面的示例中为 instance ):
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();
};
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();
};
这篇关于Javascript类中的XMLHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!