Placing JSON string into a store

南笙酒味 提交于 2019-12-11 18:13:39

问题


Simple question here. How could I place this JSON string into an Ext.data.Store?

   {
   "elements":[
      {
         "element":{
            "name":"value 1",
            "id":"element 1",
            "attributes":[
               {
                  "attrname":"id",
                  "attrvalue":"This is the ID"
               },
               {
                  "attrname":"name",
                  "attrvalue":"This is the name"
               },
               {
                  "attrname":"description",
                  "attrvalue":"This is the description"
               },
               {
                  "attrname":"table_name",
                  "attrvalue":"This is the table"
               }
            ]
         }
      }
   }

This is a simplified version of my question: Placing JSON response elements into a store- Ext JS

Cheers!


回答1:


Since the JSON is coming back from the server, the first thing you'll need to do is to deserialize it from a JSON-formatted string into an object that you can navigate. Assuming that it's valid JSON, you can simply do this by using Ext.decode().

This will give an object that has an array of objects at the "elements" key. Simply loop over the elements array and create a new model instance that can be inserted into your store.

Here's a link to a live example: https://fiddle.sencha.com/#fiddle/3u6

And here's the code from that example:

var data = YOUR_DATA_HERE,
var store = Ext.create('Ext.data.Store', {
    fields: ['id', 'name', 'description', 'table_name'],
    proxy: {
        type: 'memory'
    }
})
Ext.create('Ext.grid.Panel', {
    title: 'Test Data',
    store: store,
    columns: [{
        text: 'ID',
        dataIndex: 'id'
    }, {
        text: 'Name',
        dataIndex: 'name'
    }, {
        text: 'Description',
        dataIndex: 'description'
    }, {
        text: 'Table Name',
        dataIndex: 'table_name'
    }],
    renderTo: Ext.getBody()
});
var decoded = Ext.decode( data );
// loop over decoded data
for( var i=0; i<decoded.elements.length; i++ ) {
    var element = decoded.elements[ i ].element;
    // set implicit model
    var model = {};
    // loop over attributes
    for( var x=0; x<element.attributes.length; x++ ) {
        var attribute = element.attributes[ x ];
        model[ attribute.attrname ] = attribute.attrvalue;
    }
    // implicitly cast data as Model
    store.add( model );
}


来源:https://stackoverflow.com/questions/22056939/placing-json-string-into-a-store

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!