October 15, 2011
jQuery Code to Display Top News using YQL JSONP API Service
Many sites provide JSONP services, allowing you access to their content via a predefined API. Great source of JSONP-formatted data is the Yahoo Query Language.
Below example, we’ll use YQL JSONP API service to populate the top news from yahoo rss and display on the web page.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
// ajax request to yql public json url
url : 'http://query.yahooapis.com/v1/public/yql',
jsonp : 'callback',
// tell jQuery that we need JSON format
dataType : 'jsonp',
// tell YQL that what we want and output in JSON format
data : {
q : 'select * from rss where url ="http://rss.news.yahoo.com/rss/topstories"',
format : 'json'
},
// parse response data
success : function(data) {
$.each(data.query.results.item, function(i,data)
{
var news_data =
"<div><a href='"+data.link+"'>" + data.title + "</a>" +
data.description +"</div>";
$(news_data).appendTo("#news");
});
}
});
return false;
});
</script>
</head>
<body>
<div id="news"></div>
</body>
</html>
You can use the above code to populate the data from any JSONP services, you need to change the url, data to supply related to that particular service in the ajax request and parse the output data according to the output object.