我正在这里的 html5 Rocks 网站上关注 XMLHttpRequest2 的指南。我也在学习如何在 JavaScript 中创建类。一切似乎都是正确的,但是当我在 jsfiddle 上测试这段代码时,它会从 if 语句中返回两次“错误”,然后响应返回未定义。我怀疑这是班级的问题?
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());