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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值