Cannot read XML file using javascript other than Firefox

冷暖自知 提交于 2019-12-20 06:39:23

问题


I am using the following code to read an external xml file :

if (window.XMLHttpRequest)
   {// code for IE7+, Firefox, Chrome, Opera, Safari

   xmlhttp=new XMLHttpRequest();
   }
 else
   {// code for IE6, IE5
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
 xmlhttp.open("GET","myxmlfile.xml",false);
 xmlhttp.send();
 xmlDoc=xmlhttp.responseXML; 

But the above code seems to work only on Firefox and not on Chrome/IE/Opera.

In Chrome I am getting an error in Console as cross domain access not allowed, but my xml file, js file and html file are all in the same folder in my local hard drive.

Any help on this?

Thanks.


回答1:


You are probably testing it locally without an http server.

Fundamentally ajax requests must be made using the same domain, if you make an ajax request to a different site it will be blocked by the browser (this is a security feature to prevent people from reading the browser's owner's data from other website). Most browsers block access to the local filesystem in the same way to protect from (for example) malicious email attachments. You'll get an error like XMLHttpRequest cannot load file:///path/to/your/data.html. Origin null is not allowed by Access-Control-Allow-Origin.

If you are on Linux or Mac or have python installed the easiest way to start an http server is using the command python -m SimpleHTTPServer in root directory of your html files, then you can view them at http://localhost:8000/file.html if you're on windows then you may need to configure IIS (keep in mind IIS doesn't support certain file extensions like .json by default so you may have to configure it).

If you still want/need to test locally without having to fiddle with an http server, then you can run Chrome with --allow-file-access-from-files (either update the shortcut to the Chrome exe or run Chrome from the terminal with this switch).




回答2:


As said, you need to put your files in an http server to test correctly. You could use a local Apache instance to test it right. That way, your ajax calls won't be blocked by the browser.



来源:https://stackoverflow.com/questions/10780948/cannot-read-xml-file-using-javascript-other-than-firefox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!