4

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.

<!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>
Jaak Kütt
  • 2,566
  • 4
  • 31
  • 39
user2281107
  • 319
  • 2
  • 5
  • 14

1 Answers1

4

You can't open a local file using 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.

Amith
  • 1,424
  • 1
  • 10
  • 22
  • It does have access to the local file system. The problem is that remote viewers don't have access to *his* file system. – amphetamachine Aug 17 '13 at 20:03
  • Please suggest me the alternatives or a possible solution to this problem. I have got this code from W3C website. Thanks – user2281107 Aug 18 '13 at 03:39
  • these links can help you http://stackoverflow.com/questions/16417211/load-xml-file-content-into-div-using-jquery , http://stackoverflow.com/questions/13390722/read-xml-file-with-jquery , http://forum.jquery.com/topic/using-jquery-to-load-an-xml-file – Amith Aug 18 '13 at 04:22
  • @user2281107 you can point a web URL for an XML file. And to make it work, you can use an npm package named http-server. – ramazan polat Jan 01 '16 at 01:51
  • The only way that javascript running on a web browser allows access to a file system, is through an `` to let the user **be aware** of that specific action. When done programmatically, it can't access the file system. – Jose Rui Santos Oct 15 '19 at 11:55
  • That is why the browser's support of natively loading client-side XML documents shoud be used. However, it was broken as prohibited `data:` protocol by the interpretation of the same origin policy. So, who needs such security if there is nothing to apply it and its promoter became the intruder as he broke the functionality and thus the target user process? – Aleksey F. Nov 11 '20 at 16:07