2015-10-12 53 views
0

我不明白爲什麼我在網上得到類型錯誤(this.req是不確定的): 如果(this.req.readyState === 4){未定義的類型,當我把我的代碼對象中的JavaScript AJAX

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

感謝您的閱讀。

回答

0

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

由於這是工作。 – Fitzzz

相關問題