Skip to content

Instantly share code, notes, and snippets.

@iwek
Last active January 24, 2017 12:32
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save iwek/5599777 to your computer and use it in GitHub Desktop.
Save iwek/5599777 to your computer and use it in GitHub Desktop.
Raw JavaScript Ajax Request
//simple XHR request in pure JavaScript
function load(url, callback) {
var xhr;
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
}
xhr.onreadystatechange = ensureReadiness;
function ensureReadiness() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}
//and here is how you use it to load a json file with ajax
load('data.json', function(xhr) {
var result = xhr.responseText;
});
@jtangelder
Copy link

What's the browser support for this one?

Copy link

ghost commented Jul 2, 2016

All Browsers

Copy link

ghost commented Jul 2, 2016

But no HTTPS

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