Accessing XML File From Localhost In Javascript
I am reading XML file using javascript then display it in my html page it is working perfectly on FireFox. I googled and found that it is because my file is local in my harddisk th
Solution 1:
If you want to just run it directly from disk you won't be able to use ajax as Chrome and probably other browsers just wont allow loading of file:///
urls.
You can get around this by using a file input or drag and drop operation to get the file
Html
Select the clocks.xml file
<input type="file" id="xmlfile">
Javascript
var fileInput = document.querySelector("#xmlfile");
fileInput.addEventListener("change",function(e){
var file = fileInput.files[0];
var reader = new FileReader();
reader.onloadend = function(){
var data = reader.result;
//data will now contain the xml text
//use DOMParser to parse it
var xmlDocument = (new DOMParser()).parseFromString(data,"application/xml");
//then use the various element methods to get the elements you need
//for instance if you had a <clock> element
var clockData = xmlDocument.querySelector("clock").textContent
};
reader.readAsText(file);
})
Otherwise you would need to setup cors or load both the html and xml from your server.
Post a Comment for "Accessing XML File From Localhost In Javascript"