[英]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) { 我不明白为什么我在行上收到TypeError(this.req是未定义的):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. this.req
是未定义的,因为您正在发出异步请求,并且在您的onreadystatechange
触发时, this
不再引用您的RequestCORS
实例。
You could declare a local variable that remains in scope inside the onreadystatechange
function. 您可以声明一个保留在
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
}
}
};
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 或完全摆脱
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
}
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.