Friday, December 31, 2010

Cross Domain Issues on CouchDB and Sencha Touch

Two of the best parts of the CouchDB are the REST HTTP API and the JSON-based data structure which makes it an ideal database solution for JavaScript-based Mobile App(WebApp). While trying to use the JavaScript-based framework( likes Sencha Touch) to work with CouchDB, the first issue is always the cross-domain Ajax problem. The solution is to use JSONP, however,  the JSONP can only fulfill the "GET" part, the "POST" part has to be achieved by a "proxy" solution which against the original simplicity philosophy - JavaScript + CouchDB only! If this is a read-only App then we can live with it by using JSONP, if data write back is necessary then we have to figure out a better way! Fortunately, the PhoneGap offers the solution, since the html files under PhoneGap are called by webkit with the file://protocol, the security policy does not apply!

On the previous post - Thanksgiving Weekend Crash Course - Android, Sencha Touch, PhoneGap and CouchDB I used the JSONP(Ext.util.JSONP.request) as the example, since it can be debugged under Chrome(or Firefox) then port to the Android. To test the Ajax function(Ext.Ajax.request) I have changed the codes as following
  1. function makeAjaxRequest() {              
  2.   Ext.Ajax.request({  
  3.     url: 'http://127.0.0.1:5984/facebook/_design/acdc/_list/basic/facebook/all',  
  4.     method: "GET",  
  5.     params: {},  
  6.     success: function(res, request) {  
  7.                if (res) {  
  8.                      result = Ext.util.JSON.decode(res.responseText);  
  9.                         arr = [];  
  10.                         for (i=0; i< result.rows.length; i++){  
  11.                           arr.push({id: result.rows[i].id, img: result.rows[i].img, game:  result.rows[i].game, lastName: result.rows[i].lastName, firstName: result.rows[i].firstName});  
  12.                         }  
  13.                         layout(arr);                        
  14.                     }  
  15.                     else {  
  16.                         alert('There was an error retrieving the data.');  
  17.                     }  
  18.                 },  
  19.                 failure: function(res, request){  
  20.                  alert('Failed: ', res.responseText);  
  21.                 }  
  22.             });  
  23.         }  
  24.         
  25.   Ext.onReady(function() {  
  26.     makeAjaxRequest();  
  27.   });  
and under CouchDB a new "list" named "basic" needs to be created to work with the Ajax call, this "basic" list function will generate a JSON object instead of a Javascript function codes -


Thanksgiving Weekend Crash Course - Android, Sencha Touch, PhoneGap and CouchDB

No comments:

Post a Comment