简体   繁体   中英

undefined type when i turned my code to Object Javascript AJAX

i don't understand why i get TypeError (this.req is undefined) on line : if (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);

Thanks for reading.

this.req is undefined because you're making an asynchronous request and by the time your onreadystatechange fires this doesn't refer to your RequestCORS instance anymore.

You could declare a local variable that remains in scope inside the onreadystatechange function.

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
    }
  }
};

or use 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);

or get rid of this.req entirely

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
    }
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM