When websites provide Feeds of their content, they not only allow that content to be read through Feed readers like Google Reader but also let other sites consume that content programmatically. These feeds can be in various formats like RSS, Atom, JSON, JSONP.
Instead of scraping content from sites they don't own, developers can use RSS, Atom & JSON feeds with server-side programming languages to display that content on their own sites.
JSON stands for JavaScript Object Notation. The advantage with JSON for developers is that it can be directly translated into a JavaScript object. No parsing is necessary to get at the data.
A client-side programming language like JavaScript can however not be used to load a feed if the domain from which the feed is originating is not the same as the site where it is going to be consumed programmatically. That's were JSONP comes in.
The P in JSONP stands for "padding". A JSONP feed is same as a JSON feed except that the feed provider pads the results with a bit more information. JSONP wraps the JSON-formatted response in a function call named by the developer. It allows "cross-domain" feed content to be used via a callback function.
A JSONP feed can be consumed easily using the jQuery ajax() & getJSON() methods.
There is a great explanation of JSONP in the freely downloadable book jQuery Succinctly -
JSON with Padding (JSONP) is a technique that allows the sender of an HTTP request, where JSON is returned, to provide a name for a function that is invoked with the JSON object as a parameter of the function. This technique does not use XHR. It uses the script element so data can be pulled into any site, from any site. The purpose is to circumvent the same-source policy limitations of XMLHttpRequest.
Using the getJSON() jQuery function, you can load JSON data from another domain when a JSONP callback function is added to the URL. As an example, here is what a URL request would look like using the Flickr API.
http://api.flickr.com/services/feeds/photos_public.gne?tags=resig&tagmode=all&format=json
&jsoncallback=?
The ? value is used as a shortcut that tells jQuery to call the function that is passed as a parameter of the getJSON() function. You could replace the ? with the name of another function if you do not want to use this shortcut.
According to the ProgrammableWeb website, which has been doing a great job of cataloging web-based APIs, there are currently 360 services that offer JSONP feeds. This is good news for jQuery developers.
Related:
- Create a dead simple Twitter feed with jQuery
- Simple PHP Proxy: JavaScript finally "gets" cross-domain!
0 comments:
Post a Comment