Ext JS - Combo отображает только первую букву товаров в магазине (SimpleStore)? - PullRequest
3 голосов
/ 17 февраля 2011

Привет, у меня есть довольно простой комбинированный список Ext JS, который я просто пытаюсь привязать к массиву.Вот конфиг для комбо:

BPM.configs.ViewsCombo = {
    xtype: 'combo',
    emptyText: 'Select View',
    disableKeyFilter: true,
    triggerAction: 'all',
    displayField: 'name',
    mode: 'remote',
    render: function(combo) {
            this.store.load();
        }
    },
    store: new Ext.data.SimpleStore({
        proxy: new Ext.data.HttpProxy({
        url: '/Service.svc/GetUserViewNames',
            method: 'POST'
        }),
        root: 'GetUserViewNamesResult',
        fields: ['name']
    })
};

Вот ответ / json от вызова Ajax:

{"GetUserViewNamesResult":["something","tree"]}

Но когда я иду просматривать комбо-элементы, я вижу толькобуквы 's' и 't' в списке.Что дает ?мой возвращаемый массив в неправильном формате?

Большое спасибо.

Ответы [ 3 ]

4 голосов
/ 17 февраля 2011

ну я понял, что результат должен выглядеть так: {"GetUserViewNamesResult":[["something"],["tree"]]}.

что-то вроде отстой, потому что теперь я должен изменить способ сериализации моих серверных объектов :(

1 голос
/ 28 мая 2014

используйте это, чтобы изменить ваш массив в требуемый формат

for ( var i = 0, c = cars.length; i < c; i++ ) {
     cars[i] = [cars[i]];
}

ссылаясь на это как связать массив с архивом в порядке, чтобы заполнить комбо в extjs

0 голосов
/ 28 августа 2013

Да ExtJs все еще не имеет ридера, способного работать со списками строк. На стороне сервера (по крайней мере, в Java, C # и т. Д.) Это часто то, что вы получите при сортировке типов ENUM.

Мне пришлось написать свой собственный класс, который используется в стиле ExtJs 4.1 MVC:

/**
 * This extends basic reader and is used for converting lists of enums (e.g. ['a', 'b', 'c']) into lists of objects:
 * [ {name: 'a'}, {name:'b'}, {name:'c'}]. All models using this type of reader must have a single field called name. Or you can
 * pass a config option call 'fieldName' that will be used.
 *
 * This assumes that the server returns a standard response in the form:
 * { result: {...., "someEnum" : ['a', 'b', 'c']},
 *   total: 10,
 *   success: true,
 *   msg: 'some message'
 * }
 */
Ext.define('MY.store.EnumReader', {
    extend: 'Ext.data.reader.Json',
    alias: 'reader.enum',

    //we find the Enum value which should be a list of strings and use the 'name' property
    getData: function(data) {
        var me = this;
        //console.dir(data);
        var prop = Ext.isEmpty(this.fieldName) ? 'name' : this.fieldName;
        console.log('Using the model property: \''+ prop +'\' to set each enum item in the array');
        try {
            var enumArray = me.getRoot(data);
            //console.dir(enumArray);
            if (!Ext.isArray(enumArray)){
                console.error("expecting array of string (i.e. enum)");
                throw new Exception('not an array of strings - enum');
            }
            var enumToObjArray = Array.map(enumArray, function(item){
                    var obj = {};
                    obj[prop] = item;
                    return obj;
                }
            );
            //console.dir(enumToObjArray);
            var nodes = me.root.split('.');
            var target = data;
            var temp = "data";
            Array.forEach(nodes, function(item, index, allItems){
                temp += "['" + item + "']";
            });
            temp += " = enumToObjArray";
            //console.log('****************' + temp + '*****************');
            //evil 'eval' method. What other choice do we have?
            eval(temp);
            //console.dir(data);
            return data;
        }
        catch(ex){
            console.error('coudln\'t parse json response: ' + response.responseText);
            return this.callParent(response);
        }
    }
}, function() {
    console.log(this.getName() + ' defined');
});

Затем, если вы хотите использовать этот тип ридера в своем магазине, вы добавляете:

requires: ['My.store.EnumReader'],
...

proxy: {
    type: 'ajax',
    url:  ...
    reader: {
            type: 'enum',
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...