Проблема с заполнением ext сетки значениями JSON - PullRequest
1 голос
/ 04 июня 2011

Я новичок в Ext и у меня проблема: я пытаюсь заполнить extjs-grid данными:

    Ext.onReady(function() {
        var store = new Ext.data.JsonStore({
            root: 'topics',
            totalProperty: 'totalCount',
            idProperty: 'threadid',
            remoteSort: true,
            autoLoad: true, ///

            fields: [
                'title', 'forumtitle', 'forumid', 'author',
                {name: 'replycount', type: 'int'},
                {name: 'lastpost', mapping: 'lastpost', type: 'date', dateFormat: 'timestamp'},
                'lastposter', 'excerpt'
            ],

            proxy: new Ext.data.ScriptTagProxy({
            url:'http://10.10.10.101:8080/myproject/statusList/getJobs/2-10/search-jobname-/sort-asdf/filterjobname-123/filterusername-davs/filterstatus-completed/filtersubmdate-today',
            method : 'GET'
        })
    });

    //
    var cm = new Ext.grid.ColumnModel([
        {sortable:true, id : 'id',          dataIndex:'id'},
        {sortable:true, id : 'title',       dataIndex:'title'},
        {sortable:true, id : 'forumtitle',  dataIndex:'forumtitle'},
        {sortable:true, id : 'forumid',     dataIndex:'forumid'},
        {sortable:true, id : 'author',      dataIndex:'author'}
    ]);

    var grid = new Ext.grid.GridPanel({
        id: 'mainGrid',
        el:'mainPageGrid',
        pageSize:10,
        store:store,
        //    stripeRows: true,
        cm:cm,
        stateful: false, // skipSavingSortState
        viewConfig:{
            forceFit:true
        },
        //        width:1000,
        //        height:700,
        loadMask:true,
        frame:false,

        bbar: new Ext.PagingToolbar({
            id : 'mainGridPaginator',
            store:store,
            hideRefresh : true,
            plugins: new Ext.ux.Andrie.pPageSize({
                beforeText: 'View: ',
                afterText: '',
                addAfter: '-',
                variations: [10, 25, 50, 100, 1000]
                //comboCfg: {
                    //id: '${ dispview_widgetId }_bbar_pageSize'
                //}
            }),
            displayMsg: 'Displaying items {0} - {1} of {2}',
            emptyMsg:'No data found',
            displayInfo:true
        })
    });

    grid.render();
});

и частью Java:

@GET
@Path("/getJobs/{startFrom}-{startTo}/search-{searchType}-{searchName:.*}/" +
        "sort-{sortType}/filterjobname-{filterJobName:.*}/filterusername-{filterUsername:.*}/" +
        "filterstatus-{filterStatus:.*}/filtersubmdate-{filterSubmittedDate:.*}")
@Produces({"application/json"})
@Encoded
public String getJobs(
        @PathParam("startFrom")             String startFrom,
        @PathParam("startTo")               String startTo,
        @PathParam("searchType")            String searchType,
        @PathParam("searchName")            String searchName,
        @PathParam("sortType")              String sortType,
        @PathParam("filterJobName")         String filterJobName,
        @PathParam("filterUsername")        String filterUsername,
        @PathParam("filterStatus")          String filterStatus,
        @PathParam("filterSubmittedDate")   String filterSubmittedDate) {


    return "{totalCount:'3',topics:[{title:'XTemplate with in EditorGridPanel',threadid:'133690',username:'kpremco',userid:'272497',dateline:'1305604761',postid:'602876',forumtitle:'Ext 3x Help',forumid:'40',replycount:'2',lastpost:'1305857807',lastposter:'kpremco',excerpt:'Hi I have an EditiorGridPanel whose one column i am using XTemplate to render and another Column is Combo Box FieldWhen i render the EditorGri'}," +
                                             "{title:'IFrame error _flyweights is undefined',threadid:'133571',username:'Daz',userid:'52119',dateline:'1305533577',postid:'602456',forumtitle:'Ext 3x Help',forumid:'40',replycount:'1',lastpost:'1305857313',lastposter:'Daz',excerpt:'For Ext 330 using Firefox 4  Firebug, the following error is often happening when our app loads e._flyweights is undefined Yetthis '}," +
                                             "{title:'hellllllllllllllpwhy it doesnt fire cellclick event after I change the cell value',threadid:'133827',username:'aimer311',userid:'162000',dateline:'1305700219',postid:'603309',forumtitle:'Ext 3x Help',forumid:'40',replycount:'3',lastpost:'1305856996',lastposter:'aimer311',excerpt:'okI will discribe this problem as more detail as I canI look into this problem for a whole dayI set clicksToEdit1 to a EditorGridPanelso when I'}]}";

В результате я получаю ошибку JavaScript:

Syntax error at line 1 while loading:
totalCount:'3',topics:[{title:'XTemplate
---------------------^
expected ';', got ':'

Хотя, когда я использую URL прокси:

URL: 'http://extjs.com/forum/topics-browse-remote.php',

, который представляет ту же информацию,У меня нет проблем.

Где моя ошибка ????

PS Комментарии к первому ответу:

    return "{\"totalCount\":\"3\",\"topics\":[{\"title\":\"XTemplate with in EditorGridPanel\",\"threadid\":\"133690\",\"username\":\"kpremco\",\"userid\":\"272497\",\"dateline\":\"1305604761\",\"postid\":\"602876\",\"forumtitle\":\"Ext 3x Help\",\"forumid\":\"40\",\"replycount\":\"2\",\"lastpost\":\"1305857807\",\"lastposter\":\"kpremco\",\"excerpt\":\"Hi I have an EditiorGridPanel whose one column i am using XTemplate to render and another Column is Combo Box FieldWhen i render the EditorGri\"}," +
                                             "{\"title\":\"IFrame error _flyweights is undefined\",\"threadid\":\"133571\",\"username\":\"Daz\",\"userid\":\"52119\",\"dateline\":\"1305533577\",\"postid\":\"602456\",\"forumtitle\":\"Ext 3x Help\",\"forumid\":\"40\",\"replycount\":\"1\",\"lastpost\":\"1305857313\",\"lastposter\":\"Daz\",\"excerpt\":\"For Ext 330 using Firefox 4  Firebug, the following error is often happening when our app loads e._flyweights is undefined Yet, this \"}," +
                                             "{\"title\":\"hellllllllllllllpwhy it doesn't fire cellclick event after I change the cell value\",\"threadid\":\"133827\",\"username\":\"aimer311\",\"userid\":\"162000\",\"dateline\":\"1305700219\",\"postid\":\"603309\",\"forumtitle\":\"Ext 3x Help\",\"forumid\":\"40\",\"replycount\":\"3\",\"lastpost\":\"1305856996\",\"lastposter\":\"aimer311\",\"excerpt\":\"okI will discribe this problem as more detail as I canI look into this problem for a whole dayI set clicksToEdit1 to a EditorGridPanelso when I\"}]}";

У меня есть следующееошибка:

Syntax error at line 1 while loading:
{"totalCount":"3","topics":[{"title
-------------^
expected ';', got ':'

PS # 2.Когда я добавил «[» в начале строки ответа и «]» в конце, ошибки исчезли, но сетка не была заполнена данными

Ответы [ 2 ]

2 голосов
/ 04 июня 2011

Вы не возвращаете (действительный) JSON. За подробностями обращайтесь на сайт JSON , но, например, все ключи свойств должны быть в двойных кавычках. (Все строки также должны быть в двойных кавычках; одинарные кавычки недопустимы для строк JSON.)

Так, например, это не действительный JSON:

{totalCount:'3'}

... потому что ключ не в кавычках, а значение использует одинарные кавычки. Правильный JSON будет:

{"totalCount":"3"}

... если вы действительно хотите, чтобы 3 была строкой, или:

{"totalCount":3}

... если 3 должно быть числом.

Люди часто путают буквенную нотацию объектов JSON и JavaScript, но они разные. В частности, JSON представляет собой подмножество буквенной нотации объекта. Многие вещи, которые действительны в объектной литеральной нотации, недопустимы в JSON. В любой момент, когда вы сомневаетесь, вы можете проверить на jsonlint.com , который предоставляет правильный валидатор JSON.

0 голосов
/ 10 июня 2011

Я нашел корень проблемы.

Как я уже знал, Ext отправляет на мой веб-сервис функцию с параметром callback = [some_callback_name] (например, callback1001).Это означает, что Extjs хочет получать результаты не только в формате JSON, но и в формате callback1001 ().Когда я вернул свои данные в этом формате, все стало хорошо.

Проверочные ссылки:

...