javascript JQGrid getGridParam 数据返回空数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25804478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:03:24  来源:igfitidea点击:

JQGrid getGridParam data returns empty array

javascriptjqueryarraysjqgrid

提问by Terry

In a custom button in my pager, I call grid.jqGrid("getGridParam", "data"), "data")to get all the data in the grid but it returns empty array. When I call grid.jqGrid("getGridParam", "data")in the loadComplete function, it still returns an empty array. However if I call grid.jqGrid('getRowData')it gives me the data I am looking for. See my code below.

在我的寻呼机的自定义按钮中,我调用grid.jqGrid("getGridParam", "data"), "data")以获取网格中的所有数据,但它返回空数组。当我调用grid.jqGrid("getGridParam", "data")loadComplete 函数时,它仍然返回一个空数组。但是,如果我调用grid.jqGrid('getRowData')它会给我我正在寻找的数据。请参阅下面的我的代码。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
         pageEncoding="ISO-8859-1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/css/jquery-ui.min.css"/>
    <link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/css/ui.jqgrid.css"/>
    <!--   Overide css styling to ensure that calendar image is inline with text box -->
    <style type="text/css">.ui-jqgrid .ui-search-table .ui-search-input > input,
                            .ui-jqgrid .ui-search-table .ui-search-input > select,
                            .ui-jqgrid .ui-search-table .ui-search-input > img {vertical-align: middle; display: inline-block;}
    </style>
    <script src="${pageContext.request.contextPath}/js/jquery-1.11.0.min.js" type="text/javascript"></script>
    <script src="${pageContext.request.contextPath}/js/jquery-ui.min.js" type="text/javascript"></script>
    <script src="${pageContext.request.contextPath}/js/grid.locale-en.js" type="text/javascript"></script>
    <script src="${pageContext.request.contextPath}/js/jquery.jqGrid.min.js" type="text/javascript"></script>
    <title>Trucks Overview</title>

    <script type="text/javascript">
    jQuery().ready(function () {
        var grid = jQuery("#truck_grid");
        var orderGridDialog = $('#truck_grid_dialog');  
        var gridData;

        getUniqueNames = function(columnName) {
            var texts = grid.jqGrid('getCol', columnName, false);
            var uniqueTexts = [], textsLength = texts.length, text, i, textsMap = {}; 
            for (i=0;i<textsLength;i++) {
                text = texts[i];
                if (text != undefined && textsMap[text] === undefined) {
                    // to test whether the texts is unique we place it in the map.
                    textsMap[text] = true;
                    uniqueTexts.push(text);
                }
            }
            return uniqueTexts;
        };
        buildSearchSelect = function(uniqueNames) {
            var values=":All";
            $.each (uniqueNames, function() {
                values += ";" + this + ":" + this;
            });
            return values;
        };
        setSearchSelect = function(columnName) {
            grid.jqGrid('setColProp', columnName,
                        {   stype: 'select',
                            searchoptions: {
                                value:buildSearchSelect(getUniqueNames(columnName)),
                                sopt:['eq']
                            }
                        }
            );
        };

        var initDateWithButton = function (elem) {
            if (/^\d+%$/.test(elem.style.width)) {
                // remove % from the searching toolbar
                elem.style.width = '';
            }
            // to be able to use 'showOn' option of datepicker in advance searching dialog
            // or in the editing we have to use setTimeout
            setTimeout(function () {
                $(elem).datepicker({
                    dateFormat: 'mm/dd/yy',
                    showOn: 'button',
                    changeYear: true,
                    changeMonth: true,     
                    buttonImageOnly: true,
                    buttonImage: "images/calendar.gif",
                    buttonText: "Select date",
                    showButtonPanel: true,
                    onSelect: function (dateText, inst) {
                        inst.input.focus();
                        if (typeof (inst.id) === "string" && inst.id.substr(0, 3) === "gs_") {
                             $(inst.id).val(dateText);
                             grid[0].triggerToolbar();
                        }
                        else {
                            // to refresh the filter
                            $(inst).trigger("change");
                        }
                    }
                });
            }, 100);
        };

        grid.jqGrid({
            url: '${pageContext.request.contextPath}/getTrucksJSONAction',
            datatype: "json",
            mtype: 'GET',
            colNames: ['Truck ID', 'Status', 'Carrier Code', 'Date Created', 'Date Closed', 'T1 Status', 'Truck Arrived'],
            colModel: [
                {name: 'truckId', key:true, index: 'truckId', align: 'center', width: 100},
                {name: 'status', index: 'status', align: 'center', width: 100},
                {name: 'carrierName', index: 'carrierName', align: 'center', width: 100},
                {name: 'createdDate', index: 'createdDate', align: 'center', width: 100},
                {name: 'closedDate',  index: 'closedDate', align: 'center', width: 100},
                {name: 't1Status', sortable: false, align: 'center', width: 100, fixed: true,
                    formatter: function (celvalue) {
                        return celvalue ?
                            "<img src='http://www.clker.com/cliparts/q/j/I/0/8/d/green-circle-icon-md.png' alt='green light' style='width:15px;height:15px'/>" :
                            "<img src='http://www.iconsdb.com/icons/preview/red/circle-xxl.png' alt='red light' style='width:10px;height:10px'/>";
                    }} ,
                {name: 'truckArrived', sortable: false, align: 'center', width: 100, fixed: true,
                        formatter: function (celvalue) {
                            return celvalue ?
                                "<img src='http://www.clker.com/cliparts/q/j/I/0/8/d/green-circle-icon-md.png' alt='green light' style='width:15px;height:15px'/>" :
                                "<img src='http://www.iconsdb.com/icons/preview/red/circle-xxl.png' alt='red light' style='width:10px;height:10px'/>";
                        }}    
            ],
            rowNum: 10,
            height: 300,
            autoheight: true,
            autowidth: true,
            rowList: [10, 20, 30],
            pager: jQuery('#truck_grid_pager'),
            sortname: 'truckId',
            sortorder: "desc",
            jsonReader: {
                root: "records",
                page: "page",
                total: "total",
                records: "rows",
                repeatitems: false
            },
            viewrecords: true,
            altRows: false,
            gridview: true,
            hidegrid: false,
            multiselect:true,
            recordtext: '',
            emptyrecords: 'No Trucks',
            forceFit: true,
            caption: "Trucks Overview",
            loadComplete: function() { 
                // Reload the grid after changing paginattion
                var allRecords = grid.getGridParam('lastpage') * grid.getGridParam('records');
                grid.jqGrid('setGridParam', { 
                    recordtext: allRecords + ' Trucks(s) Found. Displaying {0} to {1}'});   
                $(this).trigger("reloadGrid");
                async: false,
                setSearchSelect('status');
                setSearchSelect('carrierName');
                grid.jqGrid('setColProp', 'truckId', {
                    searchoptions : {
                        sopt : [ 'bw' ],
                        dataInit : function(elem) {
                           $(elem).autocomplete({
                              source : getUniqueNames('truckId'),
                              delay : 0,
                              minLength : 0
                           });
                       }
                    }
                });   
                grid.jqGrid('setColProp', 'createdDate', {
                    sorttype: 'date', editable: true,
                        editoptions: { dataInit: initDateWithButton, size: 8 },
                        searchoptions: {
                            sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'],
                            dataInit: initDateWithButton
                        }
                });   
                gridData = $(this).jqGrid("getGridParam", "data");
                grid.jqGrid('filterToolbar', {autoSearch: true});
            },
        }).navGrid('#truck_grid_pager', {edit: false, add: false, del: false, search: false, refresh: true})
        .navButtonAdd('#truck_grid_pager', {caption:"Truck Arrived", buttonicon:"ui-icon-flag",  position:"first", title:"Truck Arrived",
            onClickButton: function(){ 
                var i;
                var data = grid.jqGrid("getGridParam", "data");
                var selRowIds = grid.jqGrid('getGridParam', 'selarrrow');
                for (i = 0; i < data.length; i++) {
                    if (selRowIds.indexOf(data[i].truckId) > -1) {
                        data[i].truckArrived = true;
                    }
                }
                grid.trigger("reloadGrid");
             }
        })
        .navButtonAdd('#truck_grid_pager', {caption:"Ship Confirm", buttonicon:"ui-icon-circle-check",  position:"first", title:"Ship Confirm",
            onClickButton: function(){ 
             alert("Ship has been confirmed");}
        });

        orderGridDialog.dialog({
            autoOpen: false,
            width: 1000,
            height: 400,
            draggable: false,
            show: {
                effect: "blind",
                duration: 500
            },
            hide: {
                effect: "blind",
                duration: 250
            },
            close: function(event, ui){
                orderGridDialog.text('Loading Grid...');
            }
        });
    });

</script>
</head>
<body>
<table id="truck_grid"></table>
<div id="truck_grid_pager"></div>
<div id="truck_grid_dialog" title="Orders Overview">Loading...</div>
</body>
</html>


The problem happens in the last section of the code, namely:

        .navButtonAdd('#truck_grid_pager', {caption:"Truck Arrived", buttonicon:"ui-icon-flag",  position:"first", title:"Truck Arrived",
            onClickButton: function(){ 
                var i;
                var data = grid.jqGrid("getGridParam", "data");
                var selRowIds = grid.jqGrid('getGridParam', 'selarrrow');
                for (i = 0; i < data.length; i++) {
                    if (selRowIds.indexOf(data[i].truckId) > -1) {
                        data[i].truckArrived = true;
                    }
                }
                grid.trigger("reloadGrid");
             }
        })

The second problem I have is when grid.trigger("reloadGrid")is called, the truckArrived icon is not changed from red to green as expected.

我遇到的第二个问题是当grid.trigger("reloadGrid")被调用时,truckArrived 图标没有按预期从红色变为绿色。

回答by Oleg

The internal parameter datawill be used only if one uses datatype: "local". You use datatype: "json". It means that the serverhold whole dataset only. The url: '${pageContext.request.contextPath}/getTrucksJSONAction'receive request for the pageof sorted and filtered data. The server should implement sorting, filtering/sorting and paging.

内部参数data将被用来只有一个用途datatype: "local"。你用datatype: "json". 这意味着服务器只保存整个数据集。url: '${pageContext.request.contextPath}/getTrucksJSONAction'排序和过滤数据页面的接收请求。服务器应该实现排序、过滤/排序和分页

There exists a special case: one use remote datatype ("json"or "xml"), but one uses loadonce: trueparameter additionally. In the case the server should return all unfiltered datainstead of providing the page of data. The returned data should be still sorted corresponds to sortname, sortorderparameter (which will be sent to the server as sidxand sord). jqGrid displays the first page of returned data, but it fills the internal dataparameter with whole rows of data returned from the server. After the first loading of data jqGrid changes datatypeto "local"and so the later sorting, paging and filtering of data will be like in case of datatype: "local". In the case yoou will be able to get all the data using grid.jqGrid("getGridParam", "data"), but you can do this of case afterthe data will be once loaded.

存在一种特殊情况:一种使用远程数据类型("json""xml"),但另一种使用loadonce: true参数。在这种情况下,服务器应该返回所有未过滤的数据,而不是提供数据页面。返回的数据仍应排序对应于sortname,sortorder参数(将作为sidxand发送到服务器sord)。jqGrid 显示返回数据的第一页,但它用data从服务器返回的整行数据填充内部参数。第一次加载数据后,jqGrid 就变成datatype"local",所以后面对数据的排序、分页和过滤就如datatype: "local". 在这种情况下,您将能够使用 获取所有数据grid.jqGrid("getGridParam", "data"),但您可以这样做的数据将被加载一次。