I am making a jQuery ajax call from a local file which retrieves JSON data from a webserver:
$.ajax({
type: 'GET',
url: 'http://mywebsite.com/data.json',
dataType: 'json',
success: showData
});
and I am getting the following error on chrome:
XMLHttpRequest cannot load http://mywebsite.com/data.json. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.
I have read through a lot of other answers which seem to come to the conclusion that you cannot make ajax requests from local files with chrome, so the solutions are:
but neither of these options are suitable for me.
However, when I host the JSON data on another site (myjson.com), so that the line in the ajax request reads
url: 'https://api.myjson.com/bins/myfile'
the file loads perfectly and the data is correctly displayed.
Why is the ajax request allowed to 'myjson.com' but not to 'mywebsite.com'?
Edit:
I have the line
Header set Access-Control-Allow-Origin "*"
in my apache2.conf file
What you need to do is create a .htaccess file in your document root and add the following lines to it:
<FilesMatch "\.(json)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
What the above lines do is, they allow Cross origin resource sharing for all domains on .json files thus removing the error.