Search code examples
extjsextjs3

Load JSON data into a ExtJs Grid


I am new to ExtJs and I am not able to load JSON data into the grid in any form - either inline or from a static JSON data file. Any help is highly appreciated.

Only empty grid shows up - without any data.

   var Grid1Store = new Ext.data.JsonStore({
      root: 'users',
      fields: [ 'id', 'name', 'email' ],
      autoLoad: true,
      data: { users: [ 
        { "id": 1, "name":"John Smith", "email":"jsmith@example.com"},
        { "id": 2, "name":"Anna Smith", "email":"asmith@example.com"},
        { "id": 3, "name":"Peter Smith", "email":"psmith@example.com"},
        { "id": 4, "name":"Tom Smith", "email":"tsmith@example.com"},
        { "id": 5, "name":"Andy Smith", "email":"asmith@example.com"},
        { "id": 6, "name":"Nick Smith", "email":"nsmith@example.com"}
      ]}
    });   
          var onReadyFunction = function(){

              var grid = new Ext.grid.GridPanel({
          renderTo: Ext.getBody(),
          frame: true,
          title: 'Database',
          width:300,              
          store: Grid1Store,
              columns: [
                  {text: "Id", dataIndex: 'id'},
                  {text: "Name", dataIndex: 'name'},
                  {text: "Email", dataIndex: 'email'}
              ]
                      });

      }
      Ext.onReady(onReadyFunction);

Solution

  • JsonStore doesnt take root as a config parameter. So it is useless to set a root parameter in JsonStore instance.

    Also your data should be like this to make it work.

    var Grid1Store = new Ext.data.JsonStore({
      fields: [ 'id', 'name', 'email' ],
      autoLoad: true,
      data:  [ 
        { "id": 1, "name":"John Smith", "email":"jsmith@example.com"},
        { "id": 2, "name":"Anna Smith", "email":"asmith@example.com"},
        { "id": 3, "name":"Peter Smith", "email":"psmith@example.com"},
        { "id": 4, "name":"Tom Smith", "email":"tsmith@example.com"},
        { "id": 5, "name":"Andy Smith", "email":"asmith@example.com"},
        { "id": 6, "name":"Nick Smith", "email":"nsmith@example.com"}
      ]
    });   
    

    In case you want the json structure to remain the same as you mentioned, the following is a solution. Save it as a different file - say 'data.json'. Redefine your store the following way.

    var Grid1Store = new Ext.data.JsonStore({
      fields: [ 'id', 'name', 'email' ],
      autoLoad: true,
      proxy:{
        type:'ajax',
        url:'something.json',
        reader:{
             root:'users'
            }
        }
    
    });   
    

    And that is how you use "root" - as a reader config property of proxy object.