PDA

View Full Version : Using JsonReader with sencha



testbuilder
15 Sep 2011, 12:26 AM
Hello Everyone, I am brand new with forums, with sencha and json so, may sound very naive but hopefully you guys maybe able to help me because I am pounding on this from last 48 hours. Here is what I am doing in simplest terms:

I want to read a json string from remote URL using proxy, here is the complete code I am using in my customapp.js


Ext.onReady(function(){Ext.regModel('User', {
fields: ['id', 'name', 'email']
});


var store = new Ext.data.Store({
model: 'User',
autoLoad: true,
proxy: {
type: 'ajax',
url : './test.json',
reader: {
type: 'json'
}
}
});
console.log(store.getRange());
});

and this is my test.json file:

[{"id":1,"name":"Ed Spencer","email":"ed@sencha.com"},{"id": 2,"name":"Abe Elias","email":"abe@sencha.com"}]

To point that, I simply wrote this string in a file, given it the extension of .json and saved it, nothing else I am doing here.

The response in console.log I am seeing is '[]' empty array while if I dump whole of 'store', it has nothing in data.items, that means it's not reading json? Am I doing something wrong here?

AndreaCammarata
15 Sep 2011, 12:58 AM
Hi testbuilder.
You code is ok, however there is a little conceptual error:
The store takes a little time to load depending on how much it have to load and, in any case, you have to wait that the AjaxRequest is completed.
For this reason, when the



console.log(store.getRange());


is executed, the store is still empty.
If you want to see your loaded data, you can add to your store a "load" or "datachanged" listener in this way:



var store = new Ext.data.Store({
model: 'User',
autoLoad: true,
proxy: {
type: 'ajax',
url : 'test.json',
reader: {
type: 'json'
}
},
listeners: {
load: function(){
console.log(store.getRange());
}
}
});


Hope this helps.