Custom Ext JS JsonReader for Google Ajax Search API

October 30th, 2008 by Martin

Well as long term Ext JS fan and user I of course faced with consuming external data resources like for example Google Data API or Google AJAX Search API. The last one mentioned has some really great output and layout capabilities, but I did not want them. I really need only some kind of JSON or XML interface. Google has one – ScriptTag. So after reading this post about creating custom Ext.data.JsonReader and Ext.data.ScriptTagProxy.

/** Ext Proxy for Google Ajax Search **/
Ext.namespace('GoogleAjaxSearch');
 
GoogleAjaxSearch.Proxy = Ext.extend(Ext.data.ScriptTagProxy, {
   url: 'http://ajax.googleapis.com/ajax/services/search/web',
   apiKey: null,
   cx: null,
   callbackParam: 'callback',
 
   constructor: function(config) {
      GoogleAjaxSearch.Proxy.superclass.constructor.call(this, config);
      this.on('beforeload', this.onBeforeLoad, this);
   },
 
   onBeforeLoad: function(o, params) {
      Ext.apply(params, {
         v: 	'1.0',
         rsz: 	'large',
         cx: 	this.cx,
         key: 	this.apiKey,
      }
      );
 
      return true;
   }
});
 
<span id="more-443"></span>

Based on Google AJAX Search Documentation, I created simple Ext.data.JsonReader using following code:

/** Ext JsonReader for Google Ajax Search **/
Ext.namespace('GoogleAjaxSearch');
 
GoogleAjaxSearch.Reader = Ext.extend(Ext.data.JsonReader, {
   constructor: function() {
      this.rec = Ext.data.Record.create(
      [
         'titleNoFormatting',
         'titleNoFormatting',
         'unescapedUrl',
         'content'
      ]
      );
 
      GoogleAjaxSearch.Reader.superclass.constructor.call(this, {
         totalProperty: 'responseData.cursor.estimatedResultCount',
         root: 'responseData.results',
         id: 'url'
      }, this.rec);
   }
});

Usage is simple, just include JavaScript code above and use it in your Ext.data.Store like this:

new Ext.data.Store({
      reader: new GoogleAjaxSearch.Reader(),
      proxy: new GoogleAjaxSearch.Proxy({
         apiKey: 'your_key',
         cx: 'your_custom_search_key'
      })
   	});

This simple implementation do not handle paging of multiple search results, that I will show you next time :)

 Tags

Leave a Reply

Text size: A A