我正在嘗試使用TypeScript來編寫Ajax類。打字稿碼 -TypeScript - 在TypeScript中實現的Ajax類
class Ajax {
url: string;
xmlData: string;
mode: bool;
response: string;
objHttpReq:any;
constructor (postUrl: string, postXml: string, postMode: bool) {
this.url = postUrl;
this.xmlData = postXml;
this.mode = postMode;
this.objHttpReq = new XMLHttpRequest();
this.objHttpReq.mode = this.mode;
this.objHttpReq.onreadystatechange = this.OnRStateChange;
this.objHttpReq.open("Post", this.url, this.mode);
this.objHttpReq.send(this.xmlData);
}
OnRStateChange(){
if (this.readyState==4 && this.status==200)
//here this refers to Ajax
{
//alert(xmlhttp.status);
if(this.mode == false)
{
alert(this.responseText);
}
else
{
alert(this.responseText);
}
}
}
}
遵守上面的代碼
var Ajax = (function() {
function Ajax(postUrl, postXml, postMode) {
this.url = postUrl;
this.xmlData = postXml;
this.mode = postMode;
this.objHttpReq = new XMLHttpRequest();
this.objHttpReq.mode = this.mode;
this.objHttpReq.onreadystatechange = this.OnRStateChange;
this.objHttpReq.open("Post", this.url, this.mode);
this.objHttpReq.send(this.xmlData);
}
Ajax.prototype.OnRStateChange = function() {
if(this.readyState == 4 && this.status == 200) {
//here this refers XMLHttpRequest object – works fine
if(this.mode == false) {
alert(this.responseText);
} else {
alert(this.responseText);
}
}
};
return Ajax;
})();
問題上面打字稿代碼表明錯誤的JavaScript,因爲阿賈克斯類沒有readyState的,狀態和性能的responseText。在TypeScript中編寫Ajax類的正確代碼應該是什麼?
你摸不着頭腦? –