TypeScript XMLHttp客户端

前端之家收集整理的这篇文章主要介绍了TypeScript XMLHttp客户端前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
/**
 * Logic操作基类
 */
export abstract class LCAction{
    /**
     * 序列化
     */
    public encode():any{
        let jsonData:any = {};
        for (let name in this){
            if (name.indexOf("_")!=0){
                //不以下划线开头
                let value = this[name];
                if (typeof(value)!="function"){
                    //不为函数
                    jsonData[name] = this[name];
                }
            }
        }

        return jsonData;
    }

    /**
     * 解序列化
     * @param jsonData 
     */
    public decode(jsonData:any){
        for (let name in jsonData){
            this[name] = jsonData[name];
        }
    }
}

export class LCTestRequestAction extends LCAction{
    public playerId:string;
    public playerName:string;
    public passWord:string;

    constructor(playerId:string,playerName:string,passWord:string) {
        super();
        this.playerId = playerId;
        this.playerName = playerName;
        this.passWord = passWord;
    }
}

export class LCTestResponseAction extends LCAction{
    public playerId:string;
    public playerName:string;
    public passWord:string;

    constructor(jsonData:any){
        super();
        this.decode(jsonData);
    }
}

/**
 * 网络请求回调类
 */
export class NetworkCallback{
    private object:any;
    private func:any;

    /**
     * 网络请求回调类
     * @param func 类
     * @param object  对象(若为空则认定为匿名函数)
     */
    constructor(func:any,object:any=null){
        this.func = func;
        this.object = object;
    }

    /**
     * 调用
     * @param state 状态
     * @param response 数据 
     */
    Call(state:number,response:any){
        if (this.object){
            this.func.call(this.object,state,response);
        }else{
            this.func(state,response);
        }
    }
}

/**
 * 服务端要注意开启允许跨域
 * PHP: header('Access-Control-Allow-Origin:http://xxx');
 */
export class HttpClient{
    private serverAddr:string;

    constructor(serverAddr:string){
        this.serverAddr = serverAddr;
    }

    /**
     * 发送表单
     * @param jsonData 
     */
    public PostFormData(url:string,jsonData:any,callback:NetworkCallback,async:boolean=true){
        //数据格式化
        var data = new FormData();
        for(var attr in jsonData) {
            data.append(attr,jsonData[attr]);
        }

        this.Send(url,"Post",data,false,callback,async);
    }

    /**
     * 发送Json
     * @param url 
     * @param jsonData 
     * @param onSuccessCallback 
     * @param onFailCallback 
     * @param async 
     */
    public PostJson(url:string,async:boolean=true){
        this.Send(url,JSON.stringify(jsonData),true,async);
    }

    public Get(url:string,async:boolean=true){
        for(var attr in jsonData) {
            url = this.urlParam(url,attr,jsonData[attr]);
        }
        this.Send(url,"Get",null,async);
    }

    private Send(url:string,method:string,data:any,isJsonData:boolean,async:boolean){
        //创建请求
        var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                var response = xhr.responseText;
                if (callback){
                    //是否为Json数据
                    if (isJsonData){
                        response = JSON.parse(response);
                    }
                    callback.Call(1,response);
                }
            }
        };

        //出错
        xhr.onerror = function(error){
            if (callback){
                callback.Call(0,error);
            }
        }

        //超时
        xhr.ontimeout = function(){
            if (callback){
                callback.Call(0,"Timeout");
            }
        }

        //建立连接并发送数据
        xhr.open(method,"http://"+this.serverAddr+"/"+url,async);

        //Json数据添加头
        if (isJsonData){
            xhr.setRequestHeader("Content-Type","application/json;charset=utf-8");
        }
        
        xhr.send(data);
    }

    /**
     * 添加get参数
     * @param url 
     * @param name 参数名
     * @param value 参数值
     */
    private urlParam(url,name,value) {
        url += (url.indexOf('?') == -1 ) ? '?' : '&' ; 
        url += encodeURIComponent(name) + "=" + encodeURIComponent(value);
        return url;
    }

    test(){
        let jsonData={
            playerId :"10",playerName :"10",passWord :"10",}

        let callback = new NetworkCallback(function(state,response){
            console.log(state,response);
        });

        this.PostJson("myPerson",jsonData,false);

        let lcTestRequestAction = new LCTestRequestAction("2193","dog","654321");
        let jsonStr = JSON.stringify(lcTestRequestAction.encode());
        console.log(jsonStr);

        let lcTestResponseAction = new LCTestResponseAction(JSON.parse(jsonStr));
        console.log(lcTestResponseAction);

        console.log("send!");
    }
}
原文链接:https://www.f2er.com/ajax/160613.html

猜你在找的Ajax相关文章