type HttpRequest={
mothed:string;
url:string;
param:any
timeout?:number;
}
export class HttpLoader{
private _loading:boolean=false;
private _retryTimes=3;
private _timeout=5000;
private _request:HttpRequest;
private xhr:XMLHttpRequest
public onl oad:(data:string)=>void;
public onFail:(status: number)=>void;
constructor(){
}
public load(request:HttpRequest){
this._loading=true;
//
let url=request.url;
let params=request.param;
let paramURL="";
if(params){
for(let i in params){
paramURL=paramURL.concat(i).concat("=").concat(params[i]).concat("&");
}
paramURL=encodeURI(paramURL);
}
let xhr=cc.loader.getXMLHttpRequest();
xhr.onreadystatechange = ()=> {
if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
var respone = xhr.responseText;
this.onLoad&&this.onLoad(respone);
}else{
this.onFail&&this.onFail(xhr.status);
}
this._loading=false;
};
xhr.οnerrοr=()=>{
this._loading=false;
console.log("onerror------------onreadystatechange>>",xhr.status);
this.onFail&&this.onFail(xhr.status);
}
xhr.ontimeout=()=>{
console.log("ontimeout------------onreadystatechange>>",paramURL);
}
xhr.open(request.mothed, url,true);
// xhr.setRequestHeader("Access-Control-Allow-Origin","*");
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
if (cc.sys.isNative) {
// xhr.setRequestHeader("Accept-Encoding", "gzip,deflate");
}
xhr.timeout = request.timeout||this._timeout;
xhr.send(paramURL);
}
public get loading():boolean{
return this._loading;
}
public get request():HttpRequest{
return this._request;
}
}
游戏源码参考
标签:status,loading,游戏,xhr,request,paramURL,cocoscreator,源码,._ From: https://blog.csdn.net/cocoscreator8/article/details/139287695