jqgrid重置过滤器导致崩溃

时间:2015-06-11 15:54:13

标签: javascript jquery search jqgrid

我正在研究一个jqgrid表,我设置它并且工作正常,但有一个例外 通过按高级搜索上的重置按钮(删除所有过滤器),javascript崩溃并出现错误
SyntaxError:JSON.parse:JSON数据第1行第1列的意外数据结尾 桌子是加载gif冻结。 enter image description here
来自服务器的json是好的,我的代码也没有开放括号,其他一切正常。

我使用保存列和过滤器状态但删除它们并继续崩溃。 使用

发布以下代码的jqgrid和funcs
cm = [
                {label: 'id', name: 'id', index: 'id', sortable: false, width: '50', hidden: true},
                {label: 'Actions', name: 'act', index: 'act', sortable: false, search: false, resizable: false, width: '80'},
                {label: 'UserName', name: 'User.username', index: 'User.username', sorttype: 'string', width: '140'},
                {label: 'Όνομα', name: 'FirstName', index: 'FirstName', sorttype: 'string', width: '140'},
                {label: 'Επίθετο', name: 'LastName', index: 'LastName', sorttype: 'string', width: '140'},
                {label: 'Τμήμα', name: 'Department.Description', index: 'Department.Description', sorttype: 'string', formatter: 'select', width: '180'},
                {label: 'Ρόλος', name: 'Role.Description', index: 'Role.Description', sorttype: 'string', width: '110'},
                {label: 'Τηλέφωνο', name: 'Phone', index: 'Phone', sorttype: 'string', width: '110'},
                {label: 'Κινητό', name: 'MobilePhone', index: 'MobilePhone', sorttype: 'string', width: '110'},
                {label: 'Διεύθυνση', name: 'Address', index: 'Address', sorttype: 'string', width: '180'},
                {label: 'Ημ/νία Δημ/γίας', name: 'CreatedDay', index: 'CreatedDay', width: '100',
                    sorttype: 'string',
                    searchoptions: {
                        sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'nu', 'nn', 'in', 'ni'],
                        // dataInit is the client-side event that fires upon initializing the toolbar search field for a column
                        // use it to place a third party control to customize the toolbar
                        dataInit: function (element) {
                            $(element).datepicker({
                                // id: 'orderDate_datePicker',
                                dateFormat: 'dd-mm-yy',
                                minDate: new Date(2010, 0, 1),
                                maxDate: new Date(2020, 0, 1),
                                onSelect: function () {
                                    if (this.id.substr(0, 3) === "gs_") {
                                        // in case of searching toolbar
                                        setTimeout(function () {
                                            $grid[0].triggerToolbar();
                                        }, 50);
                                    } else {
                                        // refresh the filter in case of
                                        // searching dialog
                                        $(this).trigger('change');
                                    }
                                }
                                // showOn: 'focus'
                            }
                            );
                        }
                    }
                },
                {label: 'Ώρα Δημ/γίας', name: 'CreatedTime', index: 'CreatedTime', width: '150',
                    sorttype: 'date', formatter: 'date',
                    formatoptions: {srcformat: "ISO8601Long", newformat: "d-m-Y H:i:s"},
                    searchoptions: {
                        //sopt: ['cn'],
                        // dataInit is the client-side event that fires upon initializing the toolbar search field for a column
                        // use it to place a third party control to customize the toolbar
                        dataInit: function (element) {
                            $(element).datepicker({
                                // id: 'orderDate_datePicker',
                                dateFormat: 'dd-mm-yy',
                                minDate: new Date(2010, 0, 1),
                                maxDate: new Date(2020, 0, 1),
                                onSelect: function () {
                                    if (this.id.substr(0, 3) === "gs_") {
                                        // in case of searching toolbar
                                        setTimeout(function () {
                                            $grid[0].triggerToolbar();
                                        }, 50);
                                    } else {
                                        // refresh the filter in case of
                                        // searching dialog
                                        $(this).trigger('change');
                                    }
                                }
                                // showOn: 'focus'
                            }
                            );
                        }
                    }},
            ],
                    //load options for select menu 
                    setSearchSelect = function (response) {
                        this.jqGrid("setColProp", "Role.Description", {
                            edittype: 'select',
                            editoptions:
                                    {value: response.roles},
                            stype: "select",
                            searchoptions: {
                                clearSearch: false,
                                value: response.roles,
                                sopt: ["eq"]
                            }
                        });

                        this.jqGrid("setColProp", "Department.Description", {
                            edittype: 'select',
                            editoptions:
                                    {value: response.departments},
                            stype: "select",
                            searchoptions: {
                                clearSearch: false,
                                value: response.departments,
                                sopt: ["eq"]
                            }
                        });
                    };

            //select2 init 
            filterToolbarOptions = {stringResult: true, searchOnEnter: false, defaultSearch: "cn"},
            removeAnyOption = function ($form) {
                $form.find("select.input-elm")
                        .each(function () {
                            $(this).find("option[value='']").remove();
                        });
                return true; // for beforeShowSearch only
            },
                    initSelect2 = function (element) {
                        setTimeout(function () {
                            $(element).select2({
                                // add "ui-widget" class to have the same font-family like in jQuery UI Theme
                                // add "ui-jqdialog" class to have font-size:11px like in other items of jqGrid form
                                dropdownCssClass: "ui-widget ui-jqdialog"
                            }).prev(".select2-container")
                                    .find(">.select2-choice")
                                    .find(">.select2-arrow").css("background-color", "transparent");
                            $(element).on("select2-open", function () {
                                $(element).prev(".select2-container")
                                        .find(">.select2-choice")
                                        .addClass("ui-state-default");
                            })
                                    .on("select2-close", function () {
                                        $(this).prev(".select2-container")
                                                .find(">.select2-choice")
                                                .removeClass("ui-state-default");
                                    });
                        }, 50);
                    },
                    //save table column state functions
                    numberSearchOptions = ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'nu', 'nn', 'in', 'ni'],
                    numberTemplate = {formatter: 'number', align: 'right', sorttype: 'number',
                        searchoptions: {sopt: numberSearchOptions}},
            myDefaultSearch = 'cn',
                    getColumnIndex = function (grid, columnIndex) {
                        var cm = grid.jqGrid('getGridParam', 'colModel'), i, l = cm.length;
                        for (i = 0; i < l; i++) {
                            if ((cm[i].index || cm[i].name) === columnIndex) {
                                return i; // return the colModel index
                            }
                        }
                        return -1;
                    },
                    refreshSerchingToolbar = function ($grid, myDefaultSearch) {
                        var postData = $grid.jqGrid('getGridParam', 'postData'), filters, i, l,
                                rules, rule, iCol, cm = $grid.jqGrid('getGridParam', 'colModel'),
                                cmi, control, tagName;
                        for (i = 0, l = cm.length; i < l; i++) {
                            control = $("#gs_" + $.jgrid.jqID(cm[i].name));
                            if (control.length > 0) {
                                tagName = control[0].tagName.toUpperCase();
                                if (tagName === "SELECT") { // && cmi.stype === "select"
                                    control.find("option[value='']")
                                            .attr('selected', 'selected');
                                } else if (tagName === "INPUT") {
                                    control.val('');
                                }
                            }
                        }

                        if (typeof (postData.filters) === "string" &&
                                typeof ($grid[0].ftoolbar) === "boolean" && $grid[0].ftoolbar) {

                            filters = $.parseJSON(postData.filters);
                            if (filters && filters.groupOp === "AND" && typeof (filters.groups) === "undefined") {
                                // only in case of advance searching without grouping we import filters in the
                                // searching toolbar
                                rules = filters.rules;
                                for (i = 0, l = rules.length; i < l; i++) {
                                    rule = rules[i];
                                    iCol = getColumnIndex($grid, rule.field);
                                    if (iCol >= 0) {
                                        cmi = cm[iCol];
                                        control = $("#gs_" + $.jgrid.jqID(cmi.name));
                                        if (control.length > 0 &&
                                                (((typeof (cmi.searchoptions) === "undefined" ||
                                                        typeof (cmi.searchoptions.sopt) === "undefined")
                                                        && rule.op === myDefaultSearch) ||
                                                        (typeof (cmi.searchoptions) === "object" &&
                                                                $.isArray(cmi.searchoptions.sopt) &&
                                                                cmi.searchoptions.sopt.length > 0 &&
                                                                cmi.searchoptions.sopt[0] === rule.op))) {
                                            tagName = control[0].tagName.toUpperCase();
                                            if (tagName === "SELECT") { // && cmi.stype === "select"
                                                control.find("option[value='" + $.jgrid.jqID(rule.data) + "']")
                                                        .attr('selected', 'selected');
                                            } else if (tagName === "INPUT") {
                                                control.val(rule.data);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    },
                    initDateSearch = function (elem) {
                        setTimeout(function () {
                            $(elem).datepicker({
                                dateFormat: 'dd-M-yy',
                                autoSize: true,
                                //showOn: 'button', // it dosn't work in searching dialog
                                changeYear: true,
                                changeMonth: true,
                                showButtonPanel: true,
                                showWeek: true,
                                onSelect: function () {
                                    if (this.id.substr(0, 3) === "gs_") {
                                        setTimeout(function () {
                                            $grid[0].triggerToolbar();
                                        }, 50);
                                    } else {
                                        // to refresh the filter
                                        $(this).trigger('change');
                                    }
                                }
                            });
                        }, 100);
                    },
                    saveObjectInLocalStorage = function (storageItemName, object) {
                        if (typeof window.localStorage !== 'undefined') {
                            window.localStorage.setItem(storageItemName, JSON.stringify(object));
                        }
                    },
                    removeObjectFromLocalStorage = function (storageItemName) {
                        if (typeof window.localStorage !== 'undefined') {
                            window.localStorage.removeItem(storageItemName);
                        }
                    },
                    getObjectFromLocalStorage = function (storageItemName) {
                        if (typeof window.localStorage !== 'undefined') {
                            return JSON.parse(window.localStorage.getItem(storageItemName));
                        }
                    },
                    myColumnStateName = 'ColumnChooserAndLocalStorage1.colState',
                    saveColumnState = function () {
                        var colModel = this.jqGrid('getGridParam', 'colModel'), i, l = colModel.length, colItem, cmName,
                                postData = this.jqGrid('getGridParam', 'postData'),
                                columnsState = {
                                    search: this.jqGrid('getGridParam', 'search'),
                                    page: this.jqGrid('getGridParam', 'page'),
                                    rowNum: this.jqGrid('getGridParam', 'rowNum'),
                                    sortname: this.jqGrid('getGridParam', 'sortname'),
                                    sortorder: this.jqGrid('getGridParam', 'sortorder'),
                                    permutation: this.jqGrid('getGridParam', 'remapColumns'),
                                    colStates: {}
                                },
                        colStates = columnsState.colStates;
                        if (typeof (postData.filters) !== 'undefined') {
                            columnsState.filters = postData.filters;
                        }

                        for (i = 0; i < l; i++) {
                            colItem = colModel[i];
                            cmName = colItem.name;
                            if (cmName !== 'rn' && cmName !== 'cb' && cmName !== 'subgrid') {
                                colStates[cmName] = {
                                    width: colItem.width,
                                    hidden: colItem.hidden
                                };
                            }
                        }
                        saveObjectInLocalStorage(myColumnStateName, columnsState);
                    },
                    restoreColumnState = function (colModel) {
                        var colItem, i, l = colModel.length, colStates, cmName,
                                columnsState = getObjectFromLocalStorage(myColumnStateName);
                        if (columnsState) {
                            colStates = columnsState.colStates;
                            for (i = 0; i < l; i++) {
                                colItem = colModel[i];
                                cmName = colItem.name;
                                if (cmName !== 'rn' && cmName !== 'cb' && cmName !== 'subgrid') {
                                    colModel[i] = $.extend(true, {}, colModel[i], colStates[cmName]);
                                }
                            }
                        }
                        return columnsState;
                    },
                    firstLoad = true;
            myColumnsState = restoreColumnState(cm);
            isColState = typeof (myColumnsState) !== 'undefined' && myColumnsState !== null;
            //end save table state functions

            jQuery("#jqgrid").jqGrid('searchGrid', {multipleSearch: true});
            //the grid options
            $grid = $("#jqgrid"),
                    $grid.jqGrid({
                        url: '{{ path('admin_profiles_json') }}',
                        datatype: "json",
                        colModel: cm,
                        loadonce: true,
                        width: null,
                        autowidth: true,
                        pager: '#jqGridPager',
                        toolbarfilter: true,
                        viewrecords: true,
                        pgtext: null,
                        pgbuttons: false,
                        pagination: false,
                        hoverrows: false,
                        //shrinkToFit: false,
                        rowNum: isColState ? myColumnsState.rowNum : 10000,
                        page: isColState ? myColumnsState.page : 1,
                        search: isColState ? myColumnsState.search : false,
                        postData: isColState ? {filters: myColumnsState.filters} : {},
                        sortname: isColState ? myColumnsState.sortname : 'CreatedTime',
                        sortorder: isColState ? myColumnsState.sortorder : 'desc',
                        treeGrid: false,
                        grouping: true,
                        caption: "Χρήστες",
                        multiselect: false,
                        groupingView: {
                            //groupField: ["Requestor.AlliasName"],
                            groupColumnShow: [true],
                            groupText: ['<b>{0}  count({1})</b>'],
                            groupOrder: ["asc"],
                            groupSummary: [false],
                            groupCollapse: true

                        },
                        gridComplete: function () {
                            var ids = jQuery("#jqgrid").jqGrid('getDataIDs');
                            for (var i = 0; i < ids.length; i++) {
                                var cl = ids[i];
                                be = "<button class='btn btn-xs btn-default' data-original-title='Edit Row' onclick=\"jQuery('#jqgrid').editRow('" + cl + "');\"><i class='fa fa-pencil'></i></button>";
                                se = "<button class='btn btn-xs btn-default' data-original-title='Save Row' onclick=\"jQuery('#jqgrid').saveRow('" + cl + "');\"><i class='fa fa-save'></i></button>";
                                ca = "<button class='btn btn-xs btn-default' data-original-title='Cancel' onclick=\"jQuery('#jqgrid').restoreRow('" + cl + "');\"><i class='fa fa-times'></i></button>";
                                //ce = "<button class='btn btn-xs btn-default' onclick=\"jQuery('#jqgrid').restoreRow('"+cl+"');\"><i class='fa fa-times'></i></button>";
                                //jQuery("#jqgrid").jqGrid('setRowData',ids[i],{act:be+se+ce});
                                jQuery("#jqgrid").jqGrid('setRowData', ids[i], {
                                    act: be + se + ca
                                });
                            }
                        },
                        beforeSelectRow: function (rowid, e) {

                        },
                        beforeProcessing: function (response) {
                            setSearchSelect.call($grid, response);
                            var $self = $(this),
                                    options = jQuery("#jqgrid").jqGrid('getGridParam', 'colModel'), p,
                                    //options = response.colModelOptions, p,
                                    needRecreateSearchingToolbar = false;
                            if (options !== null) {
                                for (p in options) {
                                    if (options.hasOwnProperty(p)) {
                                        if (options[p].edittype === "select") {
                                            options[p].editoptions.dataInit = initSelect2;
                                        }
                                        if (options[p].stype === "select") {
                                            options[p].searchoptions.dataInit = initSelect2;
                                        }
                                        $self.jqGrid("setColProp", p, options[p]);
                                        if (this.ftoolbar) { // filter toolbar exist
                                            needRecreateSearchingToolbar;
                                        }
                                    }
                                }
                                if (needRecreateSearchingToolbar) {
                                    $self.jqGrid("destroyFilterToolbar");
                                    $self.jqGrid("filterToolbar", filterToolbarOptions);
                                }
                            }
                        },
                        loadComplete: function () {

                            var $this = $(this);
                            if (firstLoad) {
                                firstLoad = false;
                                if (isColState && myColumnsState.permutation.length > 0) {
                                    $this.jqGrid("remapColumns", myColumnsState.permutation, true);
                                }
                                if (typeof (this.ftoolbar) !== "boolean" || !this.ftoolbar) {
                                    // create toolbar if needed
                                    $this.jqGrid('filterToolbar', {stringResult: true, searchOnEnter: false, defaultSearch: "cn"});
                                    setTimeout(function () {
                                        $grid[0].triggerToolbar();
                                    }, 50);
                                }
                            }

                            refreshSerchingToolbar($this, myDefaultSearch);
                            saveColumnState.call($this);

                        },
                        sortable: function () {
                            saveColumnState.call($grid);
                        },
                        resizeStop: function () {
                            //$("#jqGrid").trigger("resize");
                            saveColumnState.call($grid);
                        },
                        ondblClickRow: function (rowid, e)
                        {
                            var myGrid = $('#jqgrid'),
                                    selectedRowId = myGrid.jqGrid('getGridParam', 'selrow'),
                                    cellValue = myGrid.jqGrid('getCell', selectedRowId, 'id');
                            modalprofile(cellValue);
                        },
                    });
            //end grid otions

            //extend grid options
            $.extend($.jgrid.search, {
                multipleSearch: true,
                multipleGroup: true,
                recreateFilter: true,
                closeOnEscape: true,
                showQuery:true
            });

0 个答案:

没有答案