微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

TypeScript – 在TypeScript中实现的Ajax类

我正在尝试使用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.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,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);
            }
        }   
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐