Ext.js 4 окно с сервлетом формы cals, который возвращает JSON, но не может заполнить gridpanel

Я использую Ext.js 4 с MVC. У меня есть окно, которое всплывает, и запрашивает у пользователя некоторые критерии. Это окно вызывает сервлет, который возвращает данные в виде JSON и затем должен заполнить сетку. Я вижу через Firefly, что объект JSON возвращен. Однако сетка не заполняется. Причина в том, что последующий вызов сервлета сделан beign. Это потому, что у меня URL указан в двух местах. Я знаю, что это неправильно, но если один из них пропущен, я получаю сообщения об ошибках.

Это приложение / контроллер /PSLocators.js

Ext.define('MyApp.controller.PSLocators', {
    extend: 'Ext.app.Controller',
    stores: [ 'PSLocators' ],
    models: [ 'PSLocator' ],
    views : [ 'pslocator.List' ]
});

Это приложение / модель /PSLocator.js

Ext.define('MyApp.model.PSLocator', 
{
    extend: 'Ext.data.Model',
    fields: 
    [
        'id', 
        'name',
        'address',
        'city',
        'state',
        'zip',
    ]
});

Это app/store/PSLocators.js, Это первый из URL. Это тот, который не возвращает данных. Я не думаю, что у меня должен быть прокси {}, но если я удаляю прокси {}, я получаю сообщение об ошибке

uncaught exception: [Exception... "'You are using a ServerProxy but have not supplied it with a url.' when calling method: [nsIDOMEventListener::handleEvent]" 
nsresult: "0x8057001c (NS_ERROR_XPC_JS_THREW_JS_OBJECT)" 
location: "JS frame :: chrome://firebug/content/net/spy.js :: callPageHandler :: line 812" data: no]"


Ext.define('MyApp.store.PSLocators', {
    extend: 'Ext.data.Store',
    model: 'MyApp.model.PSLocator',
    autoLoad: false,    // see also activate() in grid panel
    sortOnLoad: false,  // sorted by SAS
    proxy: 
    {
        type: 'ajax',
        url: MyGlobalData.contextPath + '/PSLocator',
        reader: 
        {
            type: 'json',
            root: 'data',  // the name of the array within the JSON dataset
            totalProperty: 'results',
            successProperty: 'success'
        }
    }
});

Это app/view/pslocator/List.js, Это второй из URL. Этот URL возвращает данные правильно как JSON. Если я удаляю URL, я получаю сообщение об ошибке "uncaught исключения: URL не указан"

Ext.define('MyApp.view.pslocator.List' ,{
    extend: 'Ext.grid.Panel',
    alias : 'widget.pslocatorlist',
    store : 'PSLocators',
    title : 'Store Locator',
    id    : 'pslocator.List',

    autoScroll: true,
    height: 400,
    columnLines: true,

    initComponent: function()
    {
        this.columns = [
            {header: 'ID'          , dataIndex: 'id'        , flex: .05 , align: 'center' },
            {header: 'Name'        , dataIndex: 'name'      , flex: .20 , align: 'left'   },
            {header: 'Address'     , dataIndex: 'address'   , flex: .20 , align: 'left'   },
            {header: 'City'        , dataIndex: 'city'      , flex: .10 , align: 'left'   },
            {header: 'State'       , dataIndex: 'state'     , flex: .05 , align: 'center' },
            {header: 'Zip'         , dataIndex: 'zip'       , flex: .05 , align: 'center' }
        ];

        this.callParent(arguments);
    },

    listeners:
    {
        activate: function()
        {
            this.un('activate', arguments.callee);
            var win = new Ext.Window(
            {
                id: 'id-pslocator-window',
                title: 'Show locations near which store?',
                items: [
                {
                    xtype      : 'form',
                    id         : 'id-pslocator-form',
                    bodyPadding: 5,
                    width      : 500,
                    height     : 125,
                    autoScroll : false,

                    // The form will submit an AJAX request to this URL when submitted
                    url: MyGlobalData.contextPath + '/PSLocator',

                    layout: 'auto',

                    defaults: 
                    {
                        anchor: '100%'
                    },

                    items: [
                    {
                        xtype       : 'textfield',
                        fieldLabel  : 'Store number',
                        name        : 'pStoreNumber',
                        labelWidth  : 200,
                        width       : 300,  // includes labelWidth
                        allowBlank  : false,
                        regex       : /^([0-9]+)([ ]*)$/,  
                        regexText   : 'Must be a single unsigned integer.',
                    }
                ],

                // Reset and Submit buttons
                buttons: [
                    {
                        text: 'Reset',
                        handler: function() 
                        {
                            this.up('form').getForm().reset();
                        }
                    },
                    {
                        text: 'Submit',
                        formBind: true, //only enabled once the form is valid
                        disabled: true,
                        handler: function() 
                        {
                            var form = this.up('form').getForm();
                            if (form.isValid()) 
                            {
                                form.submit(
                                {
                                    success: function(form, action) 
                                    {
                                        console.log('In success function');
                                        var myGrid = Ext.getCmp('id-pslocator-panel');
                                        console.log('myGrid = ' + myGrid);
                                        var myStore = myGrid.getStore();
                                        console.log('myStore = ' + myStore);
                                        myStore.load();  /* requires store be defined as above */
                                        myGrid.getView().refresh();

                                        var myPopup = Ext.getCmp('id-pslocator-window');
                                        myPopup.destroy();

                                    }  // end success function
                                });  // end form submit
                            }  // end if is valid
                        }  // end handler
                    }   //  end submit
                ]   // end buttons
                }]  // end items
            }); // end win

            win.show();
            // this.store.load();
        }
    }
});  // Ext.define

Может кто-нибудь, пожалуйста, помогите или укажите мне рабочий пример (напоминание: я пытаюсь использовать архитектуру MVC.)

1 ответ

Вы должны хранить конфигурацию прокси в модели, а не в ExtJS4. Также похоже, что вы просто хотите ограничить поиск по вашим магазинам определенным номером магазина. Вам не нужно отправлять запрос POST через форму, чтобы сделать это. Вы должны добавить фильтр в ваш магазин, чтобы сервер мог вернуть правильные данные.

ОТКАЗ ОТ ОТВЕТСТВЕННОСТИ: Я не тестировал этот код, но этого должно быть достаточно, чтобы начать работу.

приложение / модель /PSLocator.js

Ext.define('MyApp.model.PSLocator', 
{
    extend: 'Ext.data.Model',
    fields: 
    [
        'id', 
        'name',
        'address',
        'city',
        'state',
        'zip',
    ],
    proxy: 
    {
        type: 'ajax',
        url: MyGlobalData.contextPath + '/PSLocator',
        reader: 
        {
            type: 'json',
            root: 'data',  // the name of the array within the JSON dataset
            totalProperty: 'results',
            successProperty: 'success'
        }
    }
});

приложение / магазин /PSLocators.js

Ext.define('MyApp.store.PSLocators', {
    extend: 'Ext.data.Store',
    model: 'MyApp.model.PSLocator',
    autoLoad: false,    // see also activate() in grid panel
    sortOnLoad: false,  // sorted by SAS,
    remoteFilter: true  // Needed so filter changes will go to the server
});

приложение / просмотр /pslocator/List.js

Ext.define('MyApp.view.pslocator.List' ,{
    extend: 'Ext.grid.Panel',
    alias : 'widget.pslocatorlist',
    store : 'PSLocators',
    title : 'Store Locator',
    id    : 'pslocator.List',

    autoScroll: true,
    height: 400,
    columnLines: true,

    initComponent: function()
    {
        this.columns = [
            {header: 'ID'          , dataIndex: 'id'        , flex: .05 , align: 'center' },
            {header: 'Name'        , dataIndex: 'name'      , flex: .20 , align: 'left'   },
            {header: 'Address'     , dataIndex: 'address'   , flex: .20 , align: 'left'   },
            {header: 'City'        , dataIndex: 'city'      , flex: .10 , align: 'left'   },
            {header: 'State'       , dataIndex: 'state'     , flex: .05 , align: 'center' },
            {header: 'Zip'         , dataIndex: 'zip'       , flex: .05 , align: 'center' }
        ];

        this.callParent(arguments);
    }
});  // Ext.define

приложение / просмотр /pslocator/Window.js

Ext.define('MyApp.view.pslocator.Window', {
    extend: 'Ext.Window',
    alias: 'widget.storeselector',
    id: 'id-pslocator-window',
    title: 'Show locations near which store?',
    items: [
    {
        xtype      : 'form',
        id         : 'id-pslocator-form',
        bodyPadding: 5,
        width      : 500,
        height     : 125,
        autoScroll : false,

        // The form will submit an AJAX request to this URL when submitted
        url: MyGlobalData.contextPath + '/PSLocator',

        layout: 'auto',

        defaults: 
        {
            anchor: '100%'
        },

        items: [
        {
            xtype       : 'textfield',
            fieldLabel  : 'Store number',
            name        : 'pStoreNumber',
            labelWidth  : 200,
            width       : 300,  // includes labelWidth
            allowBlank  : false,
            regex       : /^([0-9]+)([ ]*)$/,  
            regexText   : 'Must be a single unsigned integer.',
        }
    ],

    // Reset and Submit buttons
    buttons: [
        {
            text: 'Reset',
            handler: function() 
            {
                this.up('form').getForm().reset();
            }
        },
        {
            text: 'Submit',
            formBind: true, //only enabled once the form is valid
            disabled: true,
            handler: function() 
            {
                var form = this.up('form').getForm();
                if (form.isValid()) 
                {
                    this.fireEvent('storeselected', form.getValues().pStoreNumber);
                    this.destroy();
                }  // end if is valid
            }  // end handler
        }   //  end submit
    ]   // end buttons
    }]  // end items
});

приложение / контроллер /PSLocators.js

Ext.define('MyApp.controller.PSLocators', {
    extend: 'Ext.app.Controller',
    stores: [ 'PSLocators' ],
    models: [ 'PSLocator' ],
    views : [ 'pslocator.List' ],
    init: function() {
        this.control({
            'pslocatorlist': {
                activate: this.showStoreSelector
            },
            'storeselector': {
                storeselected: this.updatePSLocatorStore
            }
        );
    },

    showStoreSelector: function()
    {
        var win = Ext.create('MyApp.view.pslocator.Window');
        win.show();
    },

    updatePSLocatorStore: function(storeId) {
        this.getPSLocationsStore().filter('id', storeId);
        this.getPSLocationsStore().load(); // I can't remember if this step is needed.
    }
});

Я думаю, это лучшее, что я могу получить, прочитав код. Это должно дать вам представление о том, как вы можете использовать технику MVC в своих интересах и, надеюсь, вы попадете на правильный путь.

Другие вопросы по тегам