Here is our function to create a simple ajax call written in vanilla javascript (not es2015):
function ajax(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 it could be used as:
ajax('myFile.html', function(response) {
document.getElementById('container').innerHTML = response.responseText;
});
If you want to use Ecmascript 6 (also known as es2015) you can use the fetch method, which returns a promise:
fetch('myFile.json').then(function(res){
return res.json();
});
For furthner reading about es2015 Promises follow the link bellow: Promises