未定义的类型,当我把我的代码对象Javascript AJAX
undefined type when i turned my code to Object Javascript AJAX
我不明白为什么我得到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
}
}
};
相关文章:
- 元素在我的代码中不会.fadeTo.Don'I don’我不知道;s错误的JavaScript、JQuery、H
- 从我的控制器返回一个不同于200的代码以触发ajax错误,这被认为是一种好的做法吗
- 验证我的代码json
- 如何创建更好的方式来维护基于我的代码访问的最后一个页面
- 我的jquery代码不起作用.为什么?
- 为什么不是'我的函数在解析云代码中工作吗?当我在Angular和Express中测试时,它是有效的
- 我不知道为什么我的代码是错误的?又有什么错
- 为什么我的解析云代码请求'未经授权'
- 为什么不't我的ruby代码与javascript文件一起插入
- 我的html表单无法验证.请参阅代码片段中的html代码和java脚本
- 我需要一个jQuery函数来只工作在700px以上的屏幕大小,无法在我的代码中发现错误
- I'我不知道为什么我的代码没有'不起作用
- 如何使用我的Jquery代码创建委托事件侦听器
- 我不知道此代码中的这些符号是什么意思.十进制到二进制
- 什么正在取代我的'以及“;javascript代码中使用'和&”;
- 在上传之前,我可以在代码中的哪里将文件扩展名更改为小写
- 为什么动态加载的事件在我的代码中不能正常工作
- 我的Javascript代码出错
- 如何禁用我的切换按钮?这是我的代码
- 如何分离代码:我的控制器是否做了太多工作