1

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

Это приложение/контроллер/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 я получаю сообщение об ошибке «неперехваченное исключение: 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)

ответ

0

Вы должны сохранить конфигурацию прокси-сервера в модели, а не в магазине в 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 в своих интересах и, надеюсь, получите правильный путь.

+0

Спасибо за внимание. Я искренне ценю это. Я опаздываю, возвращаясь к этому, потому что вошло другое задание «спешить». (Разве это не всегда так?) Я попытался внести изменения, которые вы рекомендовали, но все еще не работает. Наверное, мое собственное понимание. Тем не менее, мне не нравится фильтрация, рекомендованная здесь. Если я не понимаю, это решение полагается на сервер, чтобы вернуть ВСЕ записи, а клиент - для фильтрации. Есть много записей, которые нужно вернуть. –

+0

Нет опции конфигурации, в которой установлено для отправки всех запросов фильтрации на сервер. –

+0

Не стоит беспокоиться Билл :) Нет там опции конфигурации, которая отправляет все запросы фильтрации на сервер. В настройке хранилища вы настраиваете следующее. remoteFilter: true Чтобы фильтры были отправлены в качестве переменных запроса в ваш веб-сервис. Нравится /PSLocator? FilterName = filterValue С вашего оригинального поста это похоже, что вы отправляете POST, чтобы отфильтровать расположение магазина в вашей форме submit. Итак, если ваше приложение на стороне сервера не поддерживает состояние? это не повлияет на данные вашего магазина. Вы хотите сделать обновление фильтра хранилища, когда правильный storeID и перезагрузить магазин. –