一份老外写的XMLHttpRequest代码多浏览器支持兼容性

时间:2021-05-25

这几天要构思用Javascript调用Asp.Net的WebService,需要到XMLHTTP来支持,但发现Opera的XMLHttpRequest很烂,实在支持不下去,后来到处找,终于发现这份代码,在Opera中是利用java.net.URL等类来实现的,不敢独享,特发上来与大家同乐。
复制代码 代码如下:
/*

Cross-BrowserXMLHttpRequestv1.2
=================================

EmulateGecko'XMLHttpRequest()'functionalityinIEandOpera.Operarequires
theSunJavaRuntimeEnvironment<http://plete
this.status=0;//HTTPstatuscodes
this.statusText='';
this._headers=[];
this._aborted=false;
this._async=true;
this._defaultCharset='ISO-8859-1';
this._getCharset=function(){
varcharset=_defaultCharset;
varcontentType=this.getResponseHeader('Content-type').toUpperCase();
val=contentType.indexOf('CHARSET=');
if(val!=-1){
charset=contentType.substring(val);
}
val=charset.indexOf(';');
if(val!=-1){
charset=charset.substring(0,val);
}
val=charset.indexOf(',');
if(val!=-1){
charset=charset.substring(0,val);
}
returncharset;
};
this.abort=function(){
this._aborted=true;
};
this.getAllResponseHeaders=function(){
returnthis.getAllResponseHeader('*');
};
this.getAllResponseHeader=function(header){
varret='';
for(vari=0;i<this._headers.length;i++){
if(header=='*'||this._headers[i].h==header){
ret+=this._headers[i].h+':'+this._headers[i].v+'\n';
}
}
returnret;
};
this.getResponseHeader=function(header){
varret=getAllResponseHeader(header);
vari=ret.indexOf('\n');
if(i!=-1){
ret=ret.substring(0,i);
}
returnret;
};
this.setRequestHeader=function(header,value){
this._headers[this._headers.length]={h:header,v:value};
};
this.open=function(method,url,async,user,password){
this.method=method;
this.url=url;
this._async=true;
this._aborted=false;
this._headers=[];
if(arguments.length>=3){
this._async=async;
}
if(arguments.length>3){
opera.postError('XMLHttpRequest.open()-user/passwordnotsupported');
}
this.readyState=1;
if(this.onreadystatechange){
this.onreadystatechange();
}
};
this.send=function(data){
if(!navigator.javaEnabled()){
alert("XMLHttpRequest.send()-Javamustbeinstalledandenabled.");
return;
}
if(this._async){
setTimeout(this._sendasync,0,this,data);
//thisisnotreallyasynchronousandwon'texecuteuntilthecurrent
//executioncontextends
}else{
this._sendsync(data);
}
}
this._sendasync=function(req,data){
if(!req._aborted){
req._sendsync(data);
}
};
this._sendsync=function(data){
this.readyState=2;
if(this.onreadystatechange){
this.onreadystatechange();
}
//openconnection
varurl=newjava.net.URL(newjava.net.URL(window.location.href),this.url);
varconn=url.openConnection();
for(vari=0;i<this._headers.length;i++){
conn.setRequestProperty(this._headers[i].h,this._headers[i].v);
}
this._headers=[];
if(this.method=='POST'){
//POSTdata
conn.setDoOutput(true);
varwr=newjava.io.OutputStreamWriter(conn.getOutputStream(),this._getCharset());
wr.write(data);
wr.flush();
wr.close();
}
//readresponseheaders
//NOTE:thegetHeaderField()methodsalwaysreturnnullsforme:(
vargotContentEncoding=false;
vargotContentLength=false;
vargotContentType=false;
vargotDate=false;
vargotExpiration=false;
vargotLastModified=false;
for(vari=0;;i++){
varhdrName=conn.getHeaderFieldKey(i);
varhdrValue=conn.getHeaderField(i);
if(hdrName==null&&hdrValue==null){
break;
}
if(hdrName!=null){
this._headers[this._headers.length]={h:hdrName,v:hdrValue};
switch(hdrName.toLowerCase()){
case'content-encoding':gotContentEncoding=true;break;
case'content-length':gotContentLength=true;break;
case'content-type':gotContentType=true;break;
case'date':gotDate=true;break;
case'expires':gotExpiration=true;break;
case'last-modified':gotLastModified=true;break;
}
}
}
//trytofillinanymissingheaderinformation
varval;
val=conn.getContentEncoding();
if(val!=null&&!gotContentEncoding)this._headers[this._headers.length]={h:'Content-encoding',v:val};
val=conn.getContentLength();
if(val!=-1&&!gotContentLength)this._headers[this._headers.length]={h:'Content-length',v:val};
val=conn.getContentType();
if(val!=null&&!gotContentType)this._headers[this._headers.length]={h:'Content-type',v:val};
val=conn.getDate();
if(val!=0&&!gotDate)this._headers[this._headers.length]={h:'Date',v:(newDate(val)).toUTCString()};
val=conn.getExpiration();
if(val!=0&&!gotExpiration)this._headers[this._headers.length]={h:'Expires',v:(newDate(val)).toUTCString()};
val=conn.getLastModified();
if(val!=0&&!gotLastModified)this._headers[this._headers.length]={h:'Last-modified',v:(newDate(val)).toUTCString()};
//readresponsedata
varreqdata='';
varstream=conn.getInputStream();
if(stream){
varreader=newjava.io.BufferedReader(newjava.io.InputStreamReader(stream,this._getCharset()));
varline;
while((line=reader.readLine())!=null){
if(this.readyState==2){
this.readyState=3;
if(this.onreadystatechange){
this.onreadystatechange();
}
}
reqdata+=line+'\n';
}
reader.close();
this.status=200;
this.statusText='OK';
this.responseText=reqdata;
this.readyState=4;
if(this.onreadystatechange){
this.onreadystatechange();
}
if(this.onload){
this.onload();
}
}else{
//error
this.status=404;
this.statusText='NotFound';
this.responseText='';
this.readyState=4;
if(this.onreadystatechange){
this.onreadystatechange();
}
if(this.onerror){
this.onerror();
}
}
};
};
}
//ActiveXObjectemulation
if(!window.ActiveXObject&&window.XMLHttpRequest){
window.ActiveXObject=function(type){
switch(type.toLowerCase()){
case'microsoft.xmlhttp':
case'msxml2.xmlhttp':
case'msxml2.xmlhttp.3.0':
case'msxml2.xmlhttp.4.0':
case'msxml2.xmlhttp.5.0':
returnnewXMLHttpRequest();
}
returnnull;
};
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章