LayaAir引擎中 Laya.HttpRequest 是专门用于处理HTTP协议网络请求而封装的类库,实质上包装的是浏览器原生的 XMLHttpRequest 对象。 HttpRequest 通过封装浏览器提供的 XMLHttpRequest 对象提供对HTTP协议的访问支持,实现 GET 、 POST 、 HEAD 等请求。
- HttpRequest 只提供以异步方式返回Web服务器响应,并以文本或二进制形式返回内容。
- HttpRequest 继承的是 EventDispatcher,因此具有事件派发功能。
项目 | 名称 | 值 |
---|---|---|
包 | Package | laya.net |
类 | Class | Laya.HttpRequest |
继承 | Inheritance | HttpRequest / 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 引用 |
url | String | [read-only] | 请求的地址 |
方法
send(url:String, data?:any, method?:String, responseType?:String, headers?:any[]|null):void
send()
方法用于发送HTTP请求
参数 | 类型 | 默认值 | 值 |
---|---|---|---|
url | String | 请求的地址,多数浏览器会实施同源安全策略,要求URL地址与包含脚本的文本具有相同的主机名称和端口。 | |
data | any | null | 发送的数据,默认值为null 。 |
method | String | get | 用于请求的HTTP方法,值包括get 、post 、head ,默认值为get 。 |
responseType | String | text | Web服务器的响应类型,可设置为text 、json 、xml 、arraybuffer ,默认值为text 。 |
headers | any[] | null | HTTP请求头信息,参数形式是key-value 的数组,key 表示头部名称,不包含空白、冒号、换行。value 是头部的值,不包含换行。 |
事件
事件 | 事件类型 | 描述 |
---|---|---|
complete | Event.type.property = Event.COMPLETE | 请求结束后调用 |
error | Event.type.property = Event.ERROR | 请求出错时调用 |
progress | Event.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);
}
});
}
}