我正在尝试使用 TypeScript 编写 Ajax 类。打字稿代码——</p>
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);
}
}
}
}
以上代码编译的JavaScript
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;
})();
上面的问题是 TypeScript 代码显示错误,因为 Ajax 类没有 readyState、status 和 responseText 属性。在 TypeScript 中编写 Ajax 类的正确代码应该是什么?