使用XMLHttpRequest2类获取请求,返回未定义的响应

get request with XMLHttpRequest2 class returning undefined response

本文关键字:返回 未定义 响应 请求 XMLHttpRequest2 获取 使用      更新时间:2023-09-26

我在这里遵循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/

你的代码有两个问题:

  1. 在initialize中,this.xhr.onload获得proccess函数执行的值,而不是函数本身。this.xhr.onload需要一个函数,()proccess的末尾,你正在执行代码,而不是委托。

  2. 如果执行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中,我们没有类,它们是原型。:)