Friday, August 10, 2012

Sencha Touch Get Yahoo News RSS using JsonP request

Hello,

Recently I was working on project where requirement was to display rss feeds from yahoo news in sencha touch application. For that we have to use JsonP request as it will be cross domain request. If we use simple Ajax request, we will get error of cross domain access and if we use JsonP request, we can not parse the response as normally RSS feed response is in XML format. So what is the solution?

Solution is to use YQL (Yahoo Query Language). YQL is the is the SQL like language that lets you search, filter data across yahoo services. We can write a select statement just like we use select statement for a table in database. We can also use joins to combine more than one results. Checkout following example.


Ext.data.JsonP.request({
            url: 'http://query.yahooapis.com/v1/public/yql',
            params: {
                q: 'select * from rss where url ="http://news.search.yahoo.com/rss?ei=UTF-8&p=USD"',
                format: 'json'
            },
            success: function (response) {
                console.log(response);
            },
            failure: function () {

            }
});

That's it and you have rss feeds in json format using cross domain jsonp request for sencha touch. Above example will return all the news related to USD currency published on yahoo news. This way you can query for any other topic.

Please note that yahoo will not return results if you try to access yql frequently from single IP. This is for security reasons. If you need uninterrupted results, you need to sign up for api and get authentication key and pass it along with the your request. Above example if of JsonP request. Same way you can use it in Ext.data.Store along with JsonP proxy. See the following code.


 Ext.define('MyApp.store.MyStore',{
       extend: 'Ext.data.Store',
       config:{
           model:'MyApp.model.MyModel',
           autoLoad: true,
            proxy : {
                type : 'jsonp',
               url: 'http://query.yahooapis.com/v1/public/yql',
                 reader: {
                  type: 'json',
                  rootProperty: 'query.results.item',
                }
            }
       }
});


Ext.getStore('MyStore').getProxy().setExtraParams({
                   q:'select * from rss where url ="http://news.search.yahoo.com/rss?ei=UTF-8&p=USD",          
                   format: 'json'
              });
Ext.getStore('MyStore').load();


This is the example of dynamic loading of store.


Hope this help you.

No comments:

Post a Comment