Skip to content

Instantly share code, notes, and snippets.

@Danilovonline
Last active December 1, 2020 14:04
Show Gist options
  • Save Danilovonline/1b87ef2ff1b1e0b19714a8b2e6246856 to your computer and use it in GitHub Desktop.
Save Danilovonline/1b87ef2ff1b1e0b19714a8b2e6246856 to your computer and use it in GitHub Desktop.
Cross-browser AJAX(pure JS)
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);
}
@Ksengine
Copy link

Ksengine commented Dec 1, 2020

it's super @Danilovonline.

why ensureReadiness?

xhr.onreadystatechange = function() {
      if (this.readyState === 4) {
        if (this.status >= 200 && this.status < 400) {
          // Success!
          success_callback(xhr)
        } else {
          // Error :(
          failure_callback(xhr)
        }
      }
    };

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment