对LAYA引擎中的 HttpRequest 进行简单封装

为了方便使用 我对这个进行了简单封装 采用了Typescript 的方式 class HTTP{ private callback:any; private caller:any; private http:Laya.HttpRequest; constructor() { this.http = new Laya.HttpRequest; }

为了方便使用 我对这个进行了简单封装  采用了Typescript 的方式

class HTTP{

    private callback:any;
    private caller:any;

    private http:Laya.HttpRequest;

    constructor() {
        this.http = new Laya.HttpRequest;
    }

    public get(url:string,caller:any,callback:any):HTTP{
        this.caller = caller;
        this.callback = callback;
        //this.http.once(Laya.Event.PROGRESS, this, this.onHttpRequestProgress);
		this.http.once(Laya.Event.COMPLETE, this, this.onHttpRequestComplete);
		this.http.once(Laya.Event.ERROR, this, this.onHttpRequestError);
        this.http.send(url, null, 'get', 'text');
        return this;
    }

     public post(url:string,data:any,contentType:string,caller:any,callback:any):HTTP{
        this.caller = caller;
        this.callback = callback;
        //this.http.once(Laya.Event.PROGRESS, this, this.onHttpRequestProgress);
		this.http.once(Laya.Event.COMPLETE, this, this.onHttpRequestComplete);
		this.http.once(Laya.Event.ERROR, this, this.onHttpRequestError);
        if(contentType==null){
            this.http.send(url, data, 'post', 'text');
        }else{
            this.http.send(url, data, 'post', 'text',["content-type",contentType]);
        }
        
        return this;
    }


    private onHttpRequestError(e: any): void {
        this.callback.apply(this.caller,[{state:500,msg:e}]);
    }

    private onHttpRequestComplete(e: any): void {
        this.callback.apply(this.caller,[{state:200,data:this.http.data}]);
    }
}

使用方法如下 GET

this.http.get('http://www.baidu.com/',this,this.getDataOnSuccess);

getDataOnSuccess(e){
        if(e.state==200){
            let d = e.data;
            console.info(d);
}else{
    alert(e.msg)
}
}

另外可以直接POST一个JSON对象 支持restful

this.http.post(Conf.HOST_NAME+"/airdefense/save",JSON.stringify({'username':'sss','pass':'abc123'}),"application/json;charset=UTF-8",this,this.onPostData);


知秋君
上一篇 2024-09-02 22:02
下一篇 2024-09-02 21:36

相关推荐