Html 使用javascript加载xml文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18292524/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 12:16:30  来源:igfitidea点击:

Load xml file using javascript

javascripthtmlxml

提问by user2281107

Nothing gets printed on the web page when I try to open an HTML file having javascript. The script inside the html code loads the xml file and tries to print some element data. I have pasted the code below. Sadly no data of file gets printed. I have used browsers IE8 and Chrome. Please let me know what is the issue.

当我尝试打开带有 javascript 的 HTML 文件时,网页上没有打印任何内容。html 代码中的脚本加载 xml 文件并尝试打印一些元素数据。我已经粘贴了下面的代码。遗憾的是没有打印文件数据。我使用过浏览器 IE8 和 Chrome。请让我知道是什么问题。

<!DOCTYPE html>
<html>
    <head>
        <script>
            function loadXMLDoc(dname)
            {
                if (window.XMLHttpRequest)
                {
                    xhttp=new XMLHttpRequest();
                }
                else
                {
                    xhttp=new ActiveXObject("Microsoft.XMLDOM");
                }

                xhttp.open("GET",dname,false);
                xhttp.send();
                return xhttp.responseXML;
            }
        </script>
    </head>
    <body>
        <script>
            xmlDoc=loadXMLDoc("file:///E:/Parser/book.xml");

            document.write(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue + "   <br>");
            document.write(xmlDoc.getElementsByTagName("authors")[0].childNodes[0].nodeValue + "<br>");

        </script>
    </body>
</html>

回答by Amith

You can't open a local file using ajax

ajax无法打开本地文件

xmlDoc=loadXMLDoc("file:///E:/Parser/book.xml"); 

this can't be performed because JavaScript running in a web browser does not have access to the local filesystem. That would a huge security risk.

无法执行此操作,因为在 Web 浏览器中运行的 JavaScript 无法访问本地文件系统。这将带来巨大的安全风险。