Last active
December 1, 2020 14:04
-
-
Save Danilovonline/1b87ef2ff1b1e0b19714a8b2e6246856 to your computer and use it in GitHub Desktop.
Cross-browser AJAX(pure JS)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function httpRequest(url, method, data, success_callback, failure_callback) { | |
var xhr; | |
var data2 = []; | |
if (typeof data == 'object') { | |
for(var index in data) { | |
if (data.hasOwnProperty(index)) { | |
data2[data2.length] =index+'='+data[index]; | |
} | |
} | |
data = data2.join("&"); | |
} | |
if(typeof XMLHttpRequest !== 'undefined') { | |
xhr = new XMLHttpRequest(); | |
} else { | |
var versions = ["MSXML2.XmlHttp.5.0", | |
"MSXML2.XmlHttp.4.0", | |
"MSXML2.XmlHttp.3.0", | |
"MSXML2.XmlHttp.2.0", | |
"Microsoft.XmlHttp"] | |
for(var i = 0, len = versions.length; i < len; i++) { | |
try { | |
xhr = new ActiveXObject(versions[i]); | |
break; | |
} | |
catch(e){} | |
} // end for | |
} | |
var ua = navigator.userAgent.toLowerCase() | |
if (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1 && ua.indexOf("webtv") == -1) { | |
xhr.onreadystatechange = ensureReadiness; | |
} else { | |
xhr.onload = function (e) { | |
if (this.status == 200) { | |
success_callback(xhr); | |
} else { | |
failure_callback(xhr); | |
} | |
}; | |
} | |
function ensureReadiness() { | |
if(xhr.readyState < 4) { | |
return; | |
} | |
if(xhr.status !== 200) { | |
return; | |
} | |
// all is well | |
if(xhr.readyState === 4) { | |
if(xhr.status !== 200) { | |
failure_callback(xhr); | |
} else { | |
success_callback(xhr); | |
} | |
} | |
} | |
if (method == 'post' || method == 'POST') { | |
method = 'POST'; | |
} else { | |
method = 'GET'; | |
} | |
xhr.open(method, url, true); | |
if (method == 'POST') { | |
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); | |
} | |
xhr.send(data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
it's super @Danilovonline.
why
ensureReadiness
?