Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
195
rated 0 times [  198] [ 3]  / answers: 1 / hits: 22203  / 7 Years ago, fri, july 7, 2017, 12:00:00

On my web server I have a folder (say the link is: www.foo.com/json/).



Inside this link, I have a json file, like foo.json. I want to access this file from another website. I've tried to research CORS but it seems pretty complicated, and I don't use any backend in on my website foo.com. I've heard you can simply use php and put this in:



<?php
header(Access-Control-Allow-Origin: *);


How do I add this to that folder that has the .json so that when I do:



$.getJSON(http://foo.com/json/foo.json, function(json) {
console.log(json
)});


It won't throw the error. I want this to be simple to let any website do it, I just don't know how to connect it all.


More From » php

 Answers
65

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.


[#57172] Thursday, July 6, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
makaylahk

Total Points: 166
Total Questions: 94
Total Answers: 117

Location: Gabon
Member since Sat, Jul 25, 2020
4 Years ago
;