javascript 如何使用xmlhttp读取本地xml文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30920325/
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
How to read local xml file using xmlhttp
提问by Sam
I have a XML file saved in my local machine and I want to read it through javascript. The following is my local xml path D:\user\xml\test1.xml
.
我在本地机器上保存了一个 XML 文件,我想通过 javascript 读取它。以下是我的本地 xml 路径D:\user\xml\test1.xml
。
<script>
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","file///D:/user/xml/test1.xml",true);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
alert(xmlDoc);
</script>
I find no response in alert. I am a newbie to XML and learning to code now. Is my system path specification correct? How to check whether my request opens the xml file and reads the input?
我在警报中没有发现任何反应。我是 XML 的新手,现在正在学习编码。我的系统路径规范是否正确?如何检查我的请求是否打开了 xml 文件并读取了输入?
回答by Andrew Sumsion
First of all you did file///...
instead of file:///...
so that may have been one of your problems.
But, more importantly, I found out it is impossible to xmlhttprequest a local file with javascript because it would be a major security riskThe only solution I can think of for you is if you write a server with nodejs or ruby on rails or something and have the server read the file and create a page on that server with the contents of that file. Then, you could send an xmlhttp request to that page.
EDIT:I forgot there is a File APIavailable in HTML5 (Thanks to Zack for pointing this out). You can use this to read the xml file, then parse it. See this pagefor how to parse xml.
首先,你做了file///...
而不是file:///...
所以这可能是你的问题之一。
但是,更重要的是,我发现不可能使用 javascript xmlhttprequest 本地文件,因为这将是一个主要的安全风险我能为您想到的唯一解决方案是,如果您使用 nodejs 或 ruby on rails 或其他东西编写服务器,并且让服务器读取文件并在该服务器上创建一个包含该文件内容的页面。然后,您可以向该页面发送 xmlhttp 请求。
编辑:我忘了 HTML5 中有一个File API可用(感谢 Zack 指出这一点)。您可以使用它来读取 xml 文件,然后解析它。请参阅此页面了解如何解析 xml。