使用单值json进入extjs组合框

时间:2012-11-13 17:14:59

标签: json extjs extjs4 extjs4.1

这是我得到的json回应。我检查了JSONLINT,它说有效,但是如果你注意到它只给了我没有列标题的值......列名是“States”。

 {"myTable":["VA","CA","CO","OK","PA","TX"]}

是否可以使用此Json加载我的组合框

items: [{
                    xtype: 'combo',
                    id: 'iccombo',
                    scope: this,
                    store: this.store,
                    mode: 'remote',
                    minChars: 0,
                    fieldLabel: 'Short State',
                    displayField: 'States',
                    valueField: 'States',
                    typeAhead: true,
                    name: 'States',
                    labelWidth: 125,
                    anchor: '95%'
                },

这是我的商店

var store = Ext.create('Ext.data.Store', {
        autoLoad: true,
        id: 'OurData',
        scope: this,
        fields: [{ name: 'States' }],
        proxy: {
            type: 'ajax',
            url: 'GetState/getS',
            reader: {
                type: 'json',
                root: 'myTable'
                idProperty: 'States'
            }
        }
    });

1 个答案:

答案 0 :(得分:4)

开箱即用Ext有几乎匹配的数组读取器,但您需要对数据格式进行调整。可以自定义阵列阅读器以获取您的数据格式并将其转换为所需的格式。对于许多无法在服务器级别进行修改的服务,这种自定义很常见,因此我们可以通过Ext JS数据框架轻松调整UI级别。

这是一个您可以使用的自定义阅读器,以及基于您的示例的实现和一个按记录显示数据的快速循环:

/**
 * A customized reader to convert a list to an array for the
 * ArrayReader to take
 */
Ext.define('Ext.ux.data.reader.JsonList', {

    extend: 'Ext.data.reader.Array',

    alias : 'reader.jsonlist',

    root: 'myTable',

    /**
     * this is really the guts of the change
     * convert an array of strings to an array of arrays of strings 
     */
    extractData: function (root) {
        var data;

        if (Ext.isArray(root) && !Ext.isArray(root[0])) {
            root.forEach(function (val, idx, all) {
                /* turn the value into an array */
                all[idx] = [val];
            })
        }

        data = root;

        /* hand the array of arrays up to the ArrayReader */
        return this.callParent([data]);
    }
});

store = Ext.create('Ext.data.Store', {
    autoLoad: true,
    id: 'OurData',
    scope: this,
    fields: [{ name: 'State' }],
    proxy: {
        /* change this back to ajax to get server data */
        type: 'memory',
        url: 'GetState/getS',
        reader: {
            type: 'jsonlist'
        }
    }, 

    /* temp data for simplified demo code */
    data: {"myTable":["VA","CA","CO","OK","PA","TX"]}
});

/* just to demo that there are six records with State as the field name: */
store.each(function (rec, id, total) {
    console.log(rec.get('State'))
});