A copy of XMLHttpRequest code written by foreigners. Multi-browser support for compatibility _ javascript skills

Source: Internet
Author: User
Tags creative commons attribution
A piece of XMLHttpRequest code written by foreigners. multiple browsers support compatibility. Over the past few days, we have to use Javascript to call Asp. net WebService, which needs to be supported by XMLHTTP, but it was found that the XMLHttpRequest of Opera is very bad and cannot be supported. Later, I searched for it everywhere and finally found that the code was used by java.net in Opera. URL and other classes to achieve, do not dare to exclusive, specially sent to enjoy with everyone.

The Code is as follows:


/*

Cross-Browser XMLHttpRequest v1.2
======================================

Emulate Gecko 'xmlhttprequest () 'functionality in IE and Opera. Opera requires
The Sun Java Runtime Environment
By Andrew Gregory
Http://www.scss.com.au/family/andrew/webdesign/xmlhttprequest/

This work is licensed under the Creative Commons Attribution License. To view
Copy of this license, visit http://creativecommons.org/licenses/by-sa/2.5/ or
Send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California
94305, USA.

Attribution: Leave my name and web address in this script intact.

Not Supported in Opera
----------------------
* User/password authentication
* ResponseXML data member

Not Fully Supported in Opera
----------------------------
* Async requests
* Abort ()
* GetAllResponseHeaders (), getAllResponseHeader (header)

*/
// IE support
If (window. ActiveXObject &&! Window. XMLHttpRequest ){
Window. XMLHttpRequest = function (){
Var msxmls = new Array (
'Msxml2. XMLHTTP.5.0 ',
'Msxml2. XMLHTTP.4.0 ',
'Msxml2. XMLHTTP.3.0 ',
'Msxml2. xmlhttp ',
'Microsoft. xmlhttp ');
For (var I = 0; I <msxmls. length; I ++ ){
Try {
Return new ActiveXObject (msxmls [I]);
} Catch (e ){
}
}
Return null;
};
}
// Gecko support
/*;-)*/
// Opera support
If (window. opera &&! Window. XMLHttpRequest ){
Window. XMLHttpRequest = function (){
This. readyState = 0; // 0 = uninitialized, 1 = loading, 2 = loaded, 3 = interactive, 4 = complete
This. status = 0; // HTTP status codes
This. statusText = '';
This. _ headers = [];
This. _ aborted = false;
This. _ async = true;
This. _ defacharcharset = 'iso-8859-1 ';
This. _ getCharset = function (){
Var charset = _ defaultCharset;
Var contentType = 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 );
}
Return charset;
};
This. abort = function (){
This. _ aborted = true;
};
This. getAllResponseHeaders = function (){
Return this. getAllResponseHeader ('*');
};
This. getAllResponseHeader = function (header ){
Var ret = '';
For (var I = 0; I <this. _ headers. length; I ++ ){
If (header = '*' | this. _ headers [I]. h = header ){
Ret + = this. _ headers [I]. h + ':' + this. _ headers [I]. v + '\ n ';
}
}
Return ret;
};
This. getResponseHeader = function (header ){
Var ret = getAllResponseHeader (header );
Var I = ret. indexOf ('\ n ');
If (I! =-1 ){
Ret = ret. substring (0, I );
}
Return ret;
};
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/password not ororted ');
}
This. readyState = 1;
If (this. onreadystatechange ){
This. onreadystatechange ();
}
};
This. send = function (data ){
If (! Navigator. javaEnabled ()){
Alert ("XMLHttpRequest. send ()-Java must be installed and enabled .");
Return;
}
If (this. _ async ){
SetTimeout (this. _ sendasync, 0, this, data );
// This is not really asynchronous and won't execute until the current
// Execution context ends
} 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 ();
}
// Open connection
Var url = new java.net. URL (new java.net. URL (window. location. href), this. url );
Var conn = url. openConnection ();
For (var I = 0; I <this. _ headers. length; I ++ ){
Conn. setRequestProperty (this. _ headers [I]. h, this. _ headers [I]. v );
}
This. _ headers = [];
If (this. method = 'post '){
// POST data
Conn. setDoOutput (true );
Var wr = new java. io. OutputStreamWriter (conn. getOutputStream (), this. _ getCharset ());
Wr. write (data );
Wr. flush ();
Wr. close ();
}
// Read response headers
// NOTE: the getHeaderField () methods always return nulls for me :(
Var gotContentEncoding = false;
Var gotContentLength = false;
Var gotContentType = false;
Var gotDate = false;
Var gotExpiration = false;
Var gotLastModified = false;
For (var I = 0; I ++ ){
Var hdrName = conn. getHeaderFieldKey (I );
Var hdrValue = 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;
}
}
}
// Try to fill in any missing header information
Var val;
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 :( new Date (val). toUTCString ()};
Val = conn. getExpiration ();
If (val! = 0 &&! GotExpiration) this. _ headers [this. _ headers. length] = {h: 'expires', v :( new Date (val). toUTCString ()};
Val = conn. getLastModified ();
If (val! = 0 &&! GotLastModified) this. _ headers [this. _ headers. length] = {h: 'Last-modified', v :( new Date (val). toUTCString ()};
// Read response data
Var reqdata = '';
Var stream = conn. getInputStream ();
If (stream ){
Var reader = new java. io. BufferedReader (new java. io. InputStreamReader (stream, this. _ getCharset ()));
Var line;
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 = 'not Found ';
This. responseText = '';
This. readyState = 4;
If (this. onreadystatechange ){
This. onreadystatechange ();
}
If (this. onerror ){
This. onerror ();
}
}
};
};
}
// ActiveXObject emulation
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 ':
Return new XMLHttpRequest ();
}
Return null;
};
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.