无法将JSON数据加载到ExtJS数据存储区中

时间:2012-01-25 13:19:48

标签: json extjs extjs4

我已经尝试了如何配置我的ExtJS数据存储区来读取传入的JSON数据的所有组合。我收到了这个JSON数据:

[{ "data_type": {"attribute1" : "value1",
                  "attribute2" : "value2",
                  "attribute3" : "value3" 
                  }
 },
 { "data_type": {"attribute1": "value4",
                  "attribute2" : "value5",
                  "attribute3" : "value6" 
                  }
 }
]

我不想解析JSON并重新格式化它以使ExtJS感到高兴,因为它似乎是多余的。我最终想要的是一个允许我这样做的数据存储:

    Ext.create('Ext.container.Container', 
    {
        id: 'junk',
        renderTo: 'slider',
        width: 960,
        height:600,
        layout: 'vbox',
        items: [
           {
              xtype: 'grid',
              title: 'foobar',
              height: 400,
              width: 700,
              store: my_store,
              viewConfig: { emptyText: 'No data' },
              columns: [
                  {
                     text: 'column1',
                     dataIndex: 'attribute1'
                  },{
                     text: 'column2',
                     dataIndex: 'attribute2'
                  },{
                     text: 'column3',
                     dataIndex: 'attribute3'
                  }
              ]
           }
        ]
    }

我知道ExtJS知道如何解析这个JSON,因为我可以这样做:

var foo = Ext.decode(data);
var good_data = foo[0].data_type.attribute1

这就像我预期的那样返回'value1'。任何人都可以帮助我理解获得数据模型和存储的神奇咒语吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

首先,您应该创建模型:

Ext.define('SomeModel', {
    extend: 'Ext.data.Model',
    fields: [
        {name: 'attribute1'},
        {name: 'attribute2'},
        {name: 'attribute3'}
    ]
});

然后,您可以通过将record属性设置为data_type来配置商店以支持您的数据格式:

var store = Ext.create('Ext.data.Store', {
    autoLoad: true,
    data : data,
    model: 'SomeModel',
    proxy: {
        type: 'memory',
        reader: {
            type: 'json',
            record: 'data_type'
        }
    }
});

工作样本:http://jsfiddle.net/lolo/WfXK6/1/

相关问题