Saturday, March 28, 2015

Ext JS - Reading a JSON File

This post shows how you can read a JSON file in your Ext JS applications.

Let's say you have the following person.json file, which contains information about a person:

{
    "name" : "Joe Bloggs",
    "age"  : "15"
}

In order to load this file, you need to define an Ext.data.Store as shown below:

Ext.define('MyApp.store.Person', {
    extend: 'Ext.data.Store',
    fields: ['name', 'age'],
    autoLoad: true,
    proxy: {
        type: 'ajax',
        url: 'person.json',
        reader: 'json',
        pageParam: false,
        startParam: false,
        limitParam: false,
        noCache: false,
        listeners: {
            exception: function(proxy, response, operation) {
                // add appropriate error handling!
                console.log("Could not read file");
            }
        }
    },

    // return the specified field of the person e.g. name.
    get: function(field) {
        return this.first() && this.first().get(field);
    }
});

Then create the store and once it has loaded, you can access the data.

var store = Ext.create('MyApp.store.Person');
store.on('load', function() {
    console.log(store.get('name'));
});

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.