未定义的类型,当我把我的代码对象Javascript AJAX

undefined type when i turned my code to Object Javascript AJAX

本文关键字:代码 我的 对象 Javascript AJAX 类型 未定义      更新时间:2023-09-26

我不明白为什么我得到TypeError(这。Req是未定义的)在线:如果(this.req。readyState === 4) {

function RequestCORS(url) {
this.url = "http://crossorigin.me/" + url;
this.req = new XMLHttpRequest();
}
RequestCORS.prototype.send = function () {
this.req.open("GET", this.url);
this.req.onreadystatechange = function() {
    if (this.req.readyState === 4) {
        if (this.req.status === 200) {
            console.log(this.req.responseText);
        } else {
            console.log("error request");
            //handleError
        }
    }
};
this.req.send();
};
function main() {
var url = "http://www.01net.com/rss/mediaplayer/replay/";
var requete = new RequestCORS(url);
requete.send();
}

window.addEventListener("load", main);

this.req是未定义的,因为您正在进行异步请求,并且当您的onreadystatechange着火时,this不再引用您的RequestCORS实例。

可以在onreadystatechange函数内部声明一个局部变量,该局部变量保持在作用域中。

var req = this.req;
this.req.onreadystatechange = function() {
  if (req.readyState === 4) {
    if (req.status === 200) {
        console.log(req.responseText);
    } else {
        console.log("error request");
        //handleError
    }
  }
};

或使用bind

this.req.onreadystatechange = function() {
  if (this.req.readyState === 4) {
    if (this.req.status === 200) {
        console.log(this.req.responseText);
    } else {
        console.log("error request");
        //handleError
    }
  }
}.bind(this);

或者完全去掉this.req

var req = new XMLHttpRequest();
req.onreadystatechange = function() {
  if (req.readyState === 4) {
    if (req.status === 200) {
        console.log(req.responseText);
    } else {
        console.log("error request");
        //handleError
    }
  }
};