Reputation: 1841
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.
Upvotes: 0
Views: 2738
Reputation: 11130
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).
Upvotes: 1
Reputation: 3436
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.
Upvotes: 0