【问题标题】:XMLHttpRequest in Javascript ClassJavascript 类中的 XMLHttpRequest
【发布时间】:2014-09-02 21:56:51
【问题描述】:

我已经定义了一个类,我正在尝试使用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。

【问题讨论】:

标签: javascript jquery ajax


【解决方案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();
};

【讨论】:

  • 谢谢。我非常感激。像魅力一样工作!
  • 但这指的是什么?
  • @SNt Javascript 作用域在我看来是一件凌乱的事情。这取决于 this 指向的单个回调。我不知道在这种情况下是什么。但调试或 console.log(this); 会给你一个提示。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-26
  • 1970-01-01
  • 2011-06-11
  • 2013-10-23
  • 2017-10-01
  • 2011-06-24
  • 1970-01-01
相关资源
最近更新 更多