2011年11月7日 星期一

Sencha Touch - load JSON data from server

HTTP API return JSON Object:

{
"returnCode":"0",
"username":null,
"pollings":[{
  "courseCode":"DB123C",
  "polling":[{
      "title":"DB123 - Polling 1",
      "pollingID":211,
      "done":true
  },{
      "title":"DB123 - Polling 2",
      "pollingID":212,
      "done":false
  }]
},{
  "courseCode":"DB125",
  "polling":[{
      "title":"DB125 - Polling 1",
      "pollingID":13,
      "done":true
  },{
      "title":"DB125 - Polling 2",
      "pollingID":14,
      "done":false
  }]
}
}


Data Model:
Ext.regModel('Polling', {
fields: [
  {name:'pollingID', type:'int'},
  {name:'title', type:'string'},
  {name:'done', type:'boolean', defaultValue:false}
        ],
belongsTo: 'Pollings'
});
Ext.regModel('Pollings', {
fields: [ 
    {name: 'courseCode', type:'string'},
],
hasMany: {model:'Polling', name:'polling'}
});
Load data store:
mps.stores.pollings = new Ext.data.Store({
model: 'Pollings',
proxy: {
type: 'ajax',
url: 'http://cfirst.ouhk.edu.hk/WebTest/GetPolling.jsp',
reader:{
type: 'json',
root: 'pollings'
}
},
autoLoad: true
}); if the url is of different domain, i.e.violate the Same Origin Policy of Ajax call, here is the get around solution:
mps.stores.pollings = new Ext.data.Store({
model: 'Pollings',
proxy: {
type: 'scripttag',
url: 'http://cfirst.ouhk.edu.hk/WebTest/GetPolling.jsp',
reader:{
type: 'json',
root: 'pollings'
}
},
autoLoad: true
});

the return type and data need to modify a bit too:
return type: 'text/javascript' instead of 'application/json'
return data need to be enclosed as if it is returning a callback function:

callbackfunction(
   
)

Ref: http://docs.sencha.com/touch/1-1/#!/api/Ext.data.ScriptTagProxy
Reading data to a List:
var courses = new Ext.List({
   store: this.stores.pollings,
   itemTpl: new Ext.XTemplate(
     '<tpl for=".">',
       '{courseCode}',
       '<tpl for="polling">',
    '{title}',
       '</tpl>',
     '</tpl>'        
  )
});

沒有留言:

張貼留言