If you attempt to load data from an external domain into a Fiddle you’re likely going to receive an XMLHttpRequest error that looks something like “Origin is not allowed by Access-Control-Allow-Origin”. You can use JSFiddle’s echo requests if you just want to simulate returning data, but sometimes you want to demonstrate an actual retrieval.
Legitimate security concerns regarding cross-site HTTP requests are the reason why you can’t simply read in any old file. However, using appropriate page headers makes accessing files from other domains possible. So, if we can set page headers in a file that returns our data, it should be accessible, right? Right!
This can’t be done using a JSON file, but it can be done in a PHP file that is setup to output JSON. The PHP code would look something like this:
<?php // Allow access from anywhere. Can be domains or * (any) header('Access-Control-Allow-Origin: http://fiddle.jshell.net'); // Allow these methods of data retrieval header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); // Allow these header types header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept'); // Create our data object in that crazy unique PHP way $arr = array(array("id" => 1, "character" => "Minstrel", "line" => "And Saint Attila raised the hand grenade up on high, saying, 'O Lord, bless this thy hand grenade, that with it thou mayst blow thine enemies to tiny bits, in thy mercy.' And the Lord did grin.")); // Return as JSON echo json_encode($arr); ?>
Note that you don’t have to use PHP. You can use just about any server side scripting language; ASP, .NET, ColdFusion, Ruby, etc., as long as you set the headers properly.
Check out an example: