使用XMLHttpRequest2类获取请求,返回未定义的响应
get request with XMLHttpRequest2 class returning undefined response
我在这里遵循html5 rocks网站上的XMLHttpRequest2指南。我也在学习如何在JavaScript中创建类。一切似乎都是正确的,但是当我在jsfiddle上测试这段代码时,它从if语句返回两次"error",然后响应返回undefined。我怀疑这是班级的问题?
function Ajax(parameters) {
this.type = parameters.type;
this.url = parameters.url;
this.format = parameters.format;
this.send = parameters.send;
this.xhr = new XMLHttpRequest();
}
Ajax.prototype.initialize = function () {
this.xhr.open(this.type, this.url, true);
this.xhr.responseType = this.format;
this.xhr.onload = this.process();
this.xhr.send(this.send);
};
Ajax.prototype.process = function () {
var self = this;
if (self.xhr.readyState === 4 && self.xhr.status === 200) {
console.log(JSON.parse(self.xhr.response));
} else {
console.log("error");
}
};
var test = new Ajax({type:"GET", url:"http://ip.jsontest.com/", format:"text", send:""});
test.initialize();
console.log(test.process());
我修改了你的代码:http://jsfiddle.net/FpskW/
你的代码有两个问题:
-
在initialize中,
this.xhr.onload
获得proccess
函数执行的值,而不是函数本身。this.xhr.onload
需要一个函数,()
在proccess
的末尾,你正在执行代码,而不是委托。 -
如果执行
this.xhr.onload = this.proccess
,则传递的是没有特定上下文的proccess
函数。这样,当XHR对象执行该函数时,该函数将具有XHR对象的上下文。当proccess
函数执行时,this
的值将是XHR对象,而不是您的对象。因此,当xhr对象尝试执行if (self.xhr.readyState === 4..
时,它会发现xhr对象没有名为xhr的属性。
你可以这样做:
Ajax.prototype.initialize = function () {
this.xhr.open(this.type, this.url, true);
this.xhr.responseType = this.format;
// we capture the context of the Ajax object
var self = this;
// and we create a lambda that executes the 'proccess' function always with the context
// of the Ajax object.
this.xhr.onload = function() {
self.process();
}
this.xhr.send(this.send);
};
就这些。
注意:在Javascript中,我们没有类,它们是原型。:)
相关文章:
- 这.SOMETHING 总是返回未定义的 - extjs
- React+Meteor:this.ops返回未定义
- 解析-为什么user.getSessionToken()返回未定义的结果
- Javascript函数返回未定义
- JavaScript-获取数据属性的值返回未定义的值
- .val()返回未定义的.text返回随机代码
- 为什么innerHTML返回“未定义”
- "这个“;正在返回未定义的
- 谷歌地图:函数返回未定义的值在console.log中运行良好
- Javascript json返回未定义
- importScripts在web工作程序中返回未定义的
- 访问嵌套 json 对象的属性将返回未定义
- NativeAppEventEmitter返回未定义的
- 我的函数返回“未定义”
- 新手Javascript函数返回未定义的石头剪刀游戏
- Nodejs模块函数返回未定义的,而不是异步的
- .getElementById在.createTextNode中返回未定义
- javascript函数不返回未定义的值
- Typeahead的Javascript类型返回未定义
- Javascript可见元素返回未定义