Showing posts with label Sencha Touch. Show all posts
Showing posts with label Sencha Touch. Show all posts

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
function makeAjaxRequest() {            
  Ext.Ajax.request({
    url: 'http://127.0.0.1:5984/facebook/_design/acdc/_list/basic/facebook/all',
    method: "GET",
    params: {},
    success: function(res, request) {
               if (res) {
                     result = Ext.util.JSON.decode(res.responseText);
                        arr = [];
                        for (i=0; i< result.rows.length; i++){
                          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});
                        }
                        layout(arr);                      
                    }
                    else {
                        alert('There was an error retrieving the data.');
                    }
                },
                failure: function(res, request){
                 alert('Failed: ', res.responseText);
                }
            });
        }
      
  Ext.onReady(function() {
    makeAjaxRequest();
  });

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