手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >一份老外写的XMLHttpRequest代码多浏览器支持兼容性
一份老外写的XMLHttpRequest代码多浏览器支持兼容性
摘要:这几天要构思用Javascript调用Asp.Net的WebService,需要到XMLHTTP来支持,但发现Opera的XMLHttpRe...

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

复制代码 代码如下:

/*

Cross-BrowserXMLHttpRequestv1.2

=================================

EmulateGecko'XMLHttpRequest()'functionalityinIEandOpera.Operarequires

theSunJavaRuntimeEnvironment<http://www.java.com/>.

byAndrewGregory

http://www.scss.com.au/family/andrew/webdesign/xmlhttprequest/

ThisworkislicensedundertheCreativeCommonsAttributionLicense.Toviewa

copyofthislicense,visithttp://creativecommons.org/licenses/by-sa/2.5/or

sendalettertoCreativeCommons,559NathanAbbottWay,Stanford,California

94305,USA.

Attribution:Leavemynameandwebaddressinthisscriptintact.

NotSupportedinOpera

----------------------

*user/passwordauthentication

*responseXMLdatamember

NotFullySupportedinOpera

----------------------------

*asyncrequests

*abort()

*getAllResponseHeaders(),getAllResponseHeader(header)

*/

//IEsupport

if(window.ActiveXObject&&!window.XMLHttpRequest){

window.XMLHttpRequest=function(){

varmsxmls=newArray(

'Msxml2.XMLHTTP.5.0',

'Msxml2.XMLHTTP.4.0',

'Msxml2.XMLHTTP.3.0',

'Msxml2.XMLHTTP',

'Microsoft.XMLHTTP');

for(vari=0;i<msxmls.length;i++){

try{

returnnewActiveXObject(msxmls[i]);

}catch(e){

}

}

returnnull;

};

}

//Geckosupport

/*;-)*/

//Operasupport

if(window.opera&&!window.XMLHttpRequest){

window.XMLHttpRequest=function(){

this.readyState=0;//0=uninitialized,1=loading,2=loaded,3=interactive,4=complete

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;

};

}

【一份老外写的XMLHttpRequest代码多浏览器支持兼容性】相关文章:

JavaScript Date对象详解

浏览器检测JS代码(兼容目前各大主流浏览器)

JavaScript代码因逗号不规范导致IE不兼容的问题

利用JS生成博文目录及CSS定制博客

js判断鼠标位置是否在某个div中的方法

简介JavaScript中的setTime()方法的使用

判断checkbox选择的个数 多浏览器

CheckBox 如何实现全选?

JavaScript中的toUTCString()方法使用详解

图片按比例缩放函数

精品推荐
分类导航