I m trying to load a local xml/ xsl file to a variable for editing. Following code works with IE and chrome . But chrome gives an warning since this call is synchronous.
function loadXMLDoc (file name){
If (window.ActiveXObject){
xhttp = new ActiveXObject(“Msxml2.XMLHTTP”);
} else {
xhttp = new XMLHttpRequest();
}
xhttp.open(“GET”,filename, false); // false is synchronous
xhttp.send();
var xml = xhttp.responseXML;
return xml;
}
But if I make this asynchronize by changing this call.
xhttp.open(“GET”,filename, false);
To true
xhttp.open(“GET”,filename, true);
or call default.
xhttp.open(“GET”,filename);
It doesn’t work in chrome and gives error in the console.
original code works in IE but not working in chrome.
I want to fix this function or write a different method which can load an local xml / xsl asynchronous and get xml/xsl to a variable In chrome.
If you want to load XML for XSLT processing then, to cater for IE, if that is needed, I think you can set xhttp.responseType = 'msxml-document'.
As for asynchronous processing and "returning" the document, consider promises e.g.
function loadDoc(url) {
return new Promise(function(resolve) {
var req = new XMLHttpRequest();
req.open("GET", url);
if (typeof XSLTProcessor === 'undefined') {
try {
req.responseType = 'msxml-document';
}
catch (e) {}
}
req.onload = function() {
resolve(this.responseXML)
}
req.send();
});
}
then you can do e.g. loadDoc('sample.xml').then(function(doc) { ... }) or for both XML and XSLT
Promise.all([loadDoc(xmlUrl), loadDoc(xslUrl)]).then(function(data) {
var xmlDoc = data[0];
var xslDoc = data[1];
Promises are not supported natively in IE but can be added by a polyfill