Laya HttpRequest

LayaAir引擎中 Laya.HttpRequest 是专门用于处理HTTP协议网络请求而封装的类库,实质上包装的是浏览器原生的 XMLHttpRequest 对象。 HttpRequest 通过封装浏览器提供的 XMLHttpRequest 对象提供对HTTP协议的访问支持,实现 GET 、 POST 、 HEAD 等请求。

  • HttpRequest 只提供以异步方式返回Web服务器响应,并以文本或二进制形式返回内容。
  • HttpRequest 继承的是 EventDispatcher,因此具有事件派发功能。
项目名称
Packagelaya.net
ClassLaya.HttpRequest
继承InheritanceHttpRequest / EventDispatcher / Object

例如:

const xhr = new Laya.HttpRequest();                      
xhr.http.timeout = 10000;

xhr.once(Laya.Even.COMPLETE, null, onCompleteHandler);
xhr.once(Laya.Event.ERROR, null, onErrorHandler);

xhr.on(Laya.Event.PROGRESS, null, onProgressHander);

xhr.send("http://xxx.xxx.com?a=xxxx&b=xxx", "", "get", "text");
// xhr.send("http://xxx.xxx.com", "a=xxxx&b=xxx", "post", "text");

function onCompleteHandler(event){}
function onErrorHandler(event){}
function onProgressHandler(event){}

注意:建议每次请求时都使用新的HttpRequest对象,因为每次调用HttpRequest对象的send()方法时会被清空之前设置的数据,并重置HTTP请求状态,这会导致之前还未返回响应的请求被重置,从而得不到之前请求的响应结果。

存取器类型读写
data*[read-only]返回的数据
http*[read-only]对象封装的原生XMLHttpRequest引用
urlString[read-only]请求的地址

方法

send(url:String, data?:any, method?:String, responseType?:String, headers?:any[]|null):void

send()方法用于发送HTTP请求

参数类型默认值
urlString请求的地址,多数浏览器会实施同源安全策略,要求URL地址与包含脚本的文本具有相同的主机名称和端口。
dataanynull发送的数据,默认值为null
methodStringget用于请求的HTTP方法,值包括getposthead,默认值为get
responseTypeStringtextWeb服务器的响应类型,可设置为textjsonxmlarraybuffer,默认值为text
headersany[]nullHTTP请求头信息,参数形式是key-value的数组,key表示头部名称,不包含空白、冒号、换行。value是头部的值,不包含换行。

事件

事件事件类型描述
completeEvent.type.property = Event.COMPLETE请求结束后调用
errorEvent.type.property = Event.ERROR请求出错时调用
progressEvent.type.property = Event.PROGRESS请求进度改变时调用

封装

使用ES6进行封装

$ vim /src/lib/Ajax.js
export default class Ajax{
    static getInstance(...args){
        if(!this._instance){
            this._instance = new Ajax(...args);
        }
        return this._instance;
    }
    constructor(...args){
        this.xhr = new Laya.HttpRequest;
        //设置超时时间
        this.xhr.http.timeout = 10000;
    }
    get(url, thisObj, callback){
        const method = "get";
        let responseType = "text";

        this.thisObj = thisObj;
        this.callback = callback;

        this.xhr.once(Laya.Event.COMPLETE, this, this.onHttpRequestComplete);
        this.xhr.once(Laya.Event.ERROR, this, this.onHttpRequestError);

        this.xhr.on(Laya.Event.PROGRESS, this, this.onHttpRequestProgress);

        this.xhr.send(url, null, method, responseType);

        return this;
    }
    post(url, data, contentType, thisObj, callback){
        const method = "post";
        let responseType = "text";

        this.thisObj = thisObj;
        this.callback = callback;
        
        this.xhr.once(Laya.Event.COMPLETE, this, this.onHttpRequestComplete);
        this.xhr.once(Laya.Event.ERROR, this, this.onHttpRequestError);

        this.xhr.on(Laya.Event.PROGRESS, this, this.onHttpRequestProgress);

        let headers = null;
        if(contentType != null){
            headers = ["content-type", contentType];
        }
        this.xhr.send(url, data, method, responseType, headers);

        return this;
    }
    onHttpRequestProgress(data){
        console.log("onHttpRequestProgress", data);
    }
    onHttpRequestComplete(data){
        console.log("onHttpRequestComplete", data, this.xhr.data);
        this.callback.apply(this.thisObj, [{state:200, data:this.xhr.data}]);
    }
    onHttpRequestError(error){
        console.log("onHttpRequestError", error, this.xhr.data);
        //onHttpRequestError [404]Not Found:http://127.0.0.1:8080/test1.json null

        const data = this.xhr.data;
        this.callback.apply(this.thisObj, [{state:500, error:error, data:data}]);
    }
}
$ bin/test.json
{"id":1, "name":"junchow"}
$ vim src/Test.js
import Ajax from "./libs/Ajax";
class Test {
    constructor() {
        Ajax.getInstance().get("http://127.0.0.1:8080/test.json", this, this.onAjaxReturn);
    }
    onAjaxReturn(data){
        console.log(data);
    }
}
new Test();

使用TS进行封装

export default class Ajax{
    private url = null;
    constructor(_url){
        this.url = _url;
    }

    private cache = {};
    public request(params:any, noToken:boolean=false):void{
        let self = this;
        //请求方法
        if(!params.method){
            params.method = "GET";
        }
        //缓存数据
        if(params.cache){
            let data = this.cache[params.url];
            if(data && params.success){
                return params.success(data);
            }
        }
        //请求数据
        let xhr = new Laya.HttpRequest();
        xhr.http.timeout = 10000;
        xhr.on(Laya.Event.PROGRESS, self, (evt:any)=>{
            console.log(evt);
        });
        xhr.once(Laya.Event.ERROR, self, (error:any)=>{
            if(error.indexOf("401") > 0){

            }else{
                if(params && params.fail){
                    params.fail(xhr.data);
                }
            }
        });
        xhr.once(Laya.Event.COMPLETE, self, (evt:any)=>{
            if(xhr.data == "401"){

            }else if(xhr.data == "404"){

            }else if(xhr.data == "500"){

            }else if(params.success){
                let data = JSON.parse(xhr.data);
                this.cache[params.url] = data;
                params.success(data);
            }
        });
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值