Reputation: 1399
I am trying to load an xml file that is on my local system. But I always get Network_err. I do the following.
function LoadXmlDoc(dName)
{
var xhttp;
if(window.XMLHttpRequest)
{
xhttp = new XMLHttpRequest();
}
else
{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
try
{
xhttp.open("GET", "file.xml", false);
xhttp.send();
}
catch(e)
{
window.alert("Unable to load the requested file.");
return;
}
return xhttp.responseXML;
}
How can I load an xml file that is on my system. all files are in same folder on my pc. Thanks
Upvotes: 1
Views: 14012
Reputation: 5500
Try:
function XMLDoc()
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
};
xmlhttp.open("GET","yourfile",true);
xmlhttp.send();
}
Updated due to simplify
Invoke XMLDoc()
and pass your file uri instead of yourfile
Note: Don't forget to run this script on server
Upvotes: 1
Reputation: 2870
You can't using XHR
due security reasons.
Check this post is very complete answer for you.
Then ckeck the HTML5 API for local files: http://www.html5rocks.com/en/tutorials/file/filesystem/
Upvotes: 1
Reputation: 176956
you might need to give proper path of xml file like this
xhttp.open("GET", "file:///C:/file.xml", false);
xhttp.send();
will do work fo ryou
full code will be like , Read more : Loading XML with Javascript
var xmlDoc;
var xmlloaded = false;
function initLibrary()
{
importXML("file:///C:/file.xml");
}
function importXML(xmlfile)
{
try
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", xmlfile, false);
}
catch (Exception)
{
var ie = (typeof window.ActiveXObject != 'undefined');
if (ie)
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
while(xmlDoc.readyState != 4) {};
xmlDoc.load(xmlfile);
readXML();
xmlloaded = true;
}
else
{
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.onload = readXML;
xmlDoc.load(xmlfile);
xmlloaded = true;
}
}
if (!xmlloaded)
{
xmlhttp.setRequestHeader('Content-Type', 'text/xml')
xmlhttp.send("");
xmlDoc = xmlhttp.responseXML;
readXML();
xmlloaded = true;
}
}
Upvotes: 1