Placing JSON response elements into a store- Ext J

2019-09-01 09:42发布

问题:

I'm wondering what the best way would be to load elements of a JSON response into a store.

What I have:

jQuery ajax request

var foodRequest = $.ajax({
    url: "MyServlet",
    type: "post",
    cache: false,
    dataType: "json",
    data: JSON.stringify(searchquery),
    error : function() {
        alert ('ERROR!! Please re-enter the search criteria and try again.');
                }
});

ajax response

{
 "Foods":[
  {
     "Food":{
        "name":"Spaghetti",
        "id":"001",
        "attributes":[
           {
              "attrname":"Price",
              "attrvalue":"18.99"
           },
           {
              "attrname":"Description",
              "attrvalue":"Spaghetti is delicious, don't argue with me"
           },
           etc...

What I want:

(each element has 4 attributes)

var grid = Ext.define('Myapp.view.Grid' ,{
    extend: 'Ext.grid.Panel',
    id: 'mygrid',', 
    initComponent: function(columns) {

        this.columns = [
            {header: 'attrname',  dataIndex: 'attrvalue', flex: 2 },
            {header: 'attrname',  dataIndex: 'attrvalue', flex: 2 },
            {header: 'attrname',  dataIndex: 'attrvalue', flex: 2 },
            {header: 'attrname',  dataIndex: 'attrvalue', flex: 2 },
            etc...

How can I take the attributes from the json response and place them into a store my grid can use, as seen above?

Cheers!

回答1:

The data you are returning looks like a tree. A normal grid works with fixed columns. In short:

  • a grid uses a store
  • the Store uses a number of fields or a Model.
  • a grid has a number of predefined columns, each column references a store(model) field by means of a dataIndex.

Now when the store loads data (either through a proxy or by manually dumping records in it). it creates a record internally. The fields on the record that are available are the fields you defined on the store or the fields you defined on the model the store uses.

Long story short, the normal setup of a grid and store is with a fixed number of columns and fields. In your case it would probably be better to use a TreePanel and store. Look at the treepanel example for this.

http://docs.sencha.com/extjs/4.0.7/extjs-build/examples/tree/treegrid.html

Good luck



标签: json Extjs