TypeScript XMLHttp客户端

  • Post author:
  • Post category:其他


/**
 * 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,jsonData:any,callback:NetworkCallback,async:boolean=true){
        this.Send(url,"Post",JSON.stringify(jsonData),true,callback,async);
    }

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

    private Send(url:string,method:string,data:any,isJsonData:boolean,callback:NetworkCallback,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,callback,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!");
    }
}



版权声明:本文为u011004567原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。