Add Access-Control-Allow-Origin: * easily to JSON
Option 1: Use PHP
You can't add it to the .json file. You would need to create a php file which returns the JSON data. A crude example might be:
/json/index.php?f=foo
header("Access-Control-Allow-Origin: *");
header("content-type: application/json");
echo file_get_contents($_REQUEST['f'].".json");
This will allow you to set the Access-Control-Allow-Origin header and return the desired json file content to your remote call:
$.getJSON("http://foo.com/json/index.php?f=foo", function(json) {
console.log(json);
});
Option 2: Use Server Configuration
Another option would be to configure the header to apply to json files in your server config. Using Apache2 you could add the following to your server config or create a .htaccess file in the /json directory to include:
<Files "*.json">
Header set Access-Control-Allow-Origin "*"
</Files>
This would include the header for all the json files automatically.
Don't access the JSON file directly, use a PHP page in the middle. So you call www.foo.com/json/, which will run the default PHP file in that folder (say index.php). Now this PHP page will set the CORS header like you mentioned:
header("Access-Control-Allow-Origin: *");
and then read the JSON file and add it to the response along with the correct MIME type:
header("content-type: application/json");