javascript 无法在javascript中加载xml文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14210507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can not load xml file in javascript
提问by Sarfraz Ahmed
I am trying to load an xml file that is on my local system. But I always get Network_err. I do the following.
我正在尝试加载本地系统上的 xml 文件。但我总是得到 Network_err。我执行以下操作。
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
如何加载系统上的 xml 文件。所有文件都在我电脑上的同一个文件夹中。谢谢
采纳答案by nanobash
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();
}
Updateddue to simplify
由于简化而更新
Invoke XMLDoc()
and pass your file uri instead of yourfile
调用XMLDoc()
并传递您的文件 uri 而不是yourfile
Note: Don't forget to run this script on server
注意:不要忘记在服务器上运行这个脚本
回答by Pranay Rana
you might need to give proper path of xml file like this
您可能需要像这样提供正确的 xml 文件路径
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
完整代码将类似于,阅读更多:使用 Javascript 加载 XML
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;
}
}
回答by Gabriel Gartz
You can't using XHR
due security reasons.
您不能使用XHR
适当的安全原因。
Check this postis very complete answer for you.
检查这篇文章对你来说是非常完整的答案。
Then ckeck the HTML5 API for local files: http://www.html5rocks.com/en/tutorials/file/filesystem/
然后检查本地文件的 HTML5 API:http: //www.html5rocks.com/en/tutorials/file/filesystem/