Cover by Cody Lindley

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

16.9. Using jQuery and JSONP

Problem

You want to consume a list of photos from Flickr’s public photo stream and display the first three images.

Solution

(function($) {
    $(document).ready(function() {
        var url     = 'http://www.flickr.com/services/feeds/photos_public.gne?
jsoncallback=?';
        var params  = { format: 'json' };
        $.getJSON(url, params, function(json) {
            if ( json.items ) {
                $.each( json.items, function(i, n) {
                    var item = json.items[i];
                    $('<a href="' + item.link + '"></a>')
                        .append('<img src="' + item.media.m + '" />')
                        .appendTo('#photos');
                    // Display the first 3 photos (returning false will
                    // Exit the loop
                    return i < 2;
                });
            }
        });
    });
})(jQuery);

Discussion

Security is a critical issue when building a website or application and especially so with the advent of Ajax. Web browsers have enforced a same origin policy on requests, which means that you’re restricted to making requests to the same domain as the page’s URL or a subdomain of the current domain. So, for example, a page served from http://www.example.com is allowed to make Ajax requests to http://www.example.com and http://x.www.example.com but not http://example.com or http://y.example.com. As the semantic Web emerged and websites such as Flickr started exposing an API for other users and services to consume, the security policy enforced by web browsers became a hindrance. One area that has never had same origin policies was the use of the script element with a src attribute. It’s possible for http://www.example.com to include ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required