gpt4 book ai didi

ajax - TypeScript - 在 TypeScript 中实现的 Ajax 类

转载 作者:搜寻专家 更新时间:2023-10-30 21:00:40 25 4
gpt4 key购买 nike

我正在尝试使用 TypeScript 编写 Ajax 类。 TypeScript 代码 –

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 类的正确代码应该是什么?

最佳答案

您只需要像这样添加适当的属性:

class Ajax {
url: string;
xmlData: string;
mode: bool;
response: string;
objHttpReq:any;
readyState: number;
status: number;
responseText: string;

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

关于ajax - TypeScript - 在 TypeScript 中实现的 Ajax 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14440220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com