簡體   English   中英

當我將代碼轉到對象Javascript AJAX時,類型為undefined

[英]undefined type when i turned my code to Object Javascript AJAX

我不明白為什么我在行上收到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);

謝謝閱讀。

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
    }
  }
};

或使用綁定

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
    }
  }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM