Calling Remote JSON Files via Javascript / jQuery

Not too long ago, I was asked to create a rolling delicious feed using their JSON data. It took me quite a while to realize what was going wrong – but the solution was obvious as soon as the problem became clear. If you’re going down the same path, maybe this bit of advice will help.

Firstly, you have to create a local reference of the JSON data. As I understand it, this has to do with the JSON server settings and security. In any event, it’s easy enough to do. Create a file, such as my delicious-json.php. All you need to put in it is this:


<?php
echo file_get_contents("http://feeds.delicious.com/v2/json/tag/hyperstudio");
?>

Easy peasy. Now you can reference it via jQuery, like so:

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>
$(document).ready(function(){
// DELICIOUS JSON -- http://feeds.delicious.com/v2/json/tag/hyperstudio
  $.getJSON('delicious-json.php', function(data){
    $.each(data, function(i, entry) {
      // Process your data here
    });
  });
});

How you use the JSON is up to you. In tomorrow’s post, I’ll describe my preferred method – cloning a model. Doing so has a lot of speed benefits, but more importantly, it separates the html from the javascript. As a consequence, any web designer can easily step in and modify the aesthetics without touching code. This facilitates the very important separation of concerns.