javascript jqGrid 分页不适用于 json 数据类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16229489/
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-27 03:48:50  来源:igfitidea点击:

jqGrid pagination not working with json datatype

javascriptjqueryjqgridpagination

提问by iboros

I can't seem to get jqGrid pagination to work. It is not making a request when I click next/prev/reloador when I try to filter. As soon as I click any of those buttons, all of the records disappear.

我似乎无法让 jqGrid 分页工作。当我单击next/prev/reload或当我尝试过滤时,它不会发出请求。只要我单击这些按钮中的任何一个,所有记录都会消失。

This is the initial request that gets sent, so you can see that all of those parameters are being passed in.

这是发送的初始请求,因此您可以看到所有这些参数都被传入。

 https://www.xxxxxxx.com/getallorders?contactId=333&bucketId=444&_search=false&nd=1366982305621&rows=2??0&page=1&sidx=PKId&sord=desc

This returns proper number of records, and if I manually execute it and pass in let's say page=2I do get proper set back. The problem seems to be that the request is not made.

这将返回正确数量的记录,如果我手动执行它并传入,假设page=2我确实得到了正确的设置。问题似乎是没有提出请求。

jQuery("#grid").jqGrid({
    url:'/GetAllOrders',
    mtype: "GET", 
    datatype: "json", 
    jsonReader: {
        root: "Rows",
        page: "Page",
        total: "Total",
        records: "Records",
        repeatitems: false,
        userdata: "UserData",
        id: "Id"
    },
    postData: {
        contactId: currentUserId,
        bucketId: currentBucketId
    },
    colNames:[
        'Id',
        'Cancel',
        'Order #',
        'Order Date',
        'Bucket', 
        'Warehouse',
        'Destination',
        'Status',
        'Tracking #',
        'Transport By',
        'Ordered By',
        'Order Items'
    ],
    colModel:[
        {name:'Id',index:'Id', width:5, align:"center", hidden: true},
        {name:'Cancel', index:'Cancel',width:80, align:"center", formatter: cancelLinkFormatter, search:false },
        {name:'OrderNumber',index:'OrderNumber', width:80, align:"center"},
        {name:'OrderDate',index:'OrderDate', width:140, align:'right'},
        {name:'Bucket',index:'Bucket', width:180, align:"center", hidden: false},
        {name:'Warehouse',index:'Warehouse', width:80, align:"center", hidden: true},
        {name:'Destination',index:'Destination', width:150},
        {name:'StatusCode', index:'StatusCode', width:100, align: 'center'},
        {name:'TrackingNumber', index:'TrackingNumber', width:100, align: 'center'},
        {name:'TransportCompany', index:'TransportCompany', width:100, align: 'center'},
        {name:'OrderedBy', index:'OrderedBy', width:100, align: 'center'},
        {name:'OrderItems', index:'OrderItems', width:100, align: 'center'}
    ],
    viewrecords: true, 
    rowNum: 20,
    autowidth: false,
    width: 860,
    height: 450,
    rowList:[10,20,30,40,50],
    pager: jQuery('#pager'),
    sortname: 'Id',
    align: 'center',
    sortorder: "desc",
    loadonce: false,
    ignoreCase: true,
    caption:"Orders"
}).navGrid('#pager',{edit:false,add:false,del:false});
setSearchSelect('StatusCode');
jQuery("#grid").jqGrid('filterToolbar', {stringResult: true, searchOnEnter: false, defaultSearch: "cn"});

This is the json response I get from the server on initial load.

这是我在初始加载时从服务器获得的 json 响应。

{
"Total":2,
"Page":1,
"Records":28,
"Rows":[
    {
        "PKId":1234,
        "OrderNumber":"XXXXXX97",
        "Cancel":"Cancel",
        "OrderDate":"Jul 11 2012 12:37PM",
        "Warehouse":"",
        "Bucket":"xxxxxxxx",
        "StatusCode":"Shipped Complete",
        "StatusLink":"View Info",
        "TrackingNumber":"xxxxxxx",
        "TransportCompany":"xxxxxxxx",
        "Destination":"xxxxxxx",
        "BucketId":110,
        "ShippingEmail":"xxxxxxxx",
        "OrderedBy":"xxxxxxxx",
        "OrderItem":"xxxxxxx"
    },
    .... MORE DATA HERE ... 20 OBJECTS ALL-TOGETHER WITHIN Rows Array
    {
        "PKId":13434,
        "OrderNumber":"XXXXXX97",
        "Cancel":"Cancel",
        "OrderDate":"Jul 11 2012 12:37PM",
        "Warehouse":"",
        "Bucket":"xxxxxxxx",
        "StatusCode":"Shipped Complete",
        "StatusLink":"View Info",
        "TrackingNumber":"xxxxxxx",
        "TransportCompany":"xxxxxxxx",
        "Destination":"xxxxxxx",
        "BucketId":110,
        "ShippingEmail":"xxxxxxxx",
        "OrderedBy":"xxxxxxxx",
        "OrderItem":"xxxxxxx"
    },
],
"UserData":null
}

Any suggestions?

有什么建议?

Btw, the pagination and filtering was working just fine when I used loadonce: trueand when I loaded all data at once, however, due to too many records I simply have to switch to server-side.

顺便说一句,当我使用loadonce: true和一次加载所有数据时,分页和过滤工作得很好,但是,由于记录太多,我只需要切换到服务器端。

EDITI found the problem. First of all, I am sorry for not including the rest of the code. You see, I also had loadCompleteand that was causing the problem for me. Code in the question will work, so I want to thank everyone for participating.

编辑我发现了问题。首先,我很抱歉没有包含其余的代码。你看,我也有loadComplete,这给我造成了问题。问题中的代码会起作用,所以我要感谢大家的参与。

This is the loadCompletethat caused the problem. Once I removed it it started paging properly.

这就是loadComplete导致问题的原因。一旦我删除它,它就开始正确分页。

        loadComplete: function() {
        setParamsOnComplete();
        var myGrid = jQuery("#grid");
        var ids = myGrid.getDataIDs();
        for (var i = 0, idCount = ids.length; i < idCount; i++) {
            jQuery("#"+ids[i]+" a",myGrid[0]).click(function(e) {
                var hash=e.currentTarget.hash;// string like "#?id=0"
                if (hash.substring(0,6) === "#S?id=") {
                    var id = hash.substring(6,hash.length);
                    var text = this.textContent || this.innerText;
                    dialog.dialog({ title: 'Status Information', 
                        buttons:{   Ok: function() {
                                        jQuery( this ).dialog("close");
                                    }
                                },
                        open:   function() {
                                    jQuery('.ui-dialog-buttonpane').find('button:contains("Ok")').css('font-size', '10px');
                                }          
                    });
                    dialog.dialog('open');
                }
                if (hash.substring(0,6) === "#C?id=") {
                    var id = hash.substring(6,hash.length);
                    var text = this.textContent || this.innerText;
                    var changed = false;
                    var additionalMesages = "";
                    jQuery.post("DataFetcher.asp", { 'action': "cancelOrder", 'id':id }, function(xml) {
                        changed = (xml === 'True');
                        additionalMesages = xml;
                    }).success(function(){ 
                        if (changed){
                            showDialogCustomTitle("Success", "You've successfully cancelled the order " + id + ".");
                            jQuery("#grid").setGridParam({datatype:'xml', page:1}).trigger('reloadGrid');
                        }else if (additionalMesages.split("_")[1] == "2"){
                            showDialogCustomTitle("Error", additionalMesages.split("_")[2]);
                        }else if (additionalMesages.split("_")[1] == "1"){
                            showDialogCustomTitle("Error", additionalMesages.split("_")[2]);
                        }
                    });
                }
                //e.preventDefault();
            });
        }  
    },

Next task for me is to perhaps figure out why loadCompletecause the problem.

我的下一个任务可能是找出loadComplete导致问题的原因。

EDIT 2Found the first issue with loadComplete. I was too tired last night to notice it, but the leftover code from the period when this grid was populated with xml and paged on client side definitely caused the problems. Thank you all for involvement again. :)

编辑 2发现第一个问题loadComplete。昨晚我太累了,没有注意到它,但是这个网格被 xml 填充并在客户端分页时的剩余代码肯定会导致问题。再次感谢大家的参与。:)

jQuery("#grid").setGridParam({datatype:'xml', page:1}).trigger('reloadGrid');

jQuery("#grid").setGridParam({datatype:'xml', page:1}).trigger('reloadGrid');

回答by Ajo Koshy

Since you have set loadonce:false, the request for paging and filtering try to get processed at the server side. Since that may not probably happening in your case, there will be no data to return to and set in the jqGrid.

由于您已设置loadonce:false,因此分页和过滤请求会尝试在服务器端进行处理。由于在您的情况下可能不会发生这种情况,因此将没有数据要返回和设置在 jqGrid 中。

If you are using loadonce:falseand datatype:"json"jqGrid option then your server must implement the pagination of your grid. The server receives some parameters which is appended to the url in case of the 'GET'requests or sent in the HTTP body in case of "POST"requests namely : rows, page, sidx, sord.

如果您使用loadonce:falsedatatype:"json"jqGrid 选项,那么您的服务器必须实现网格的分页。服务器接收一些参数,这些参数在'GET'请求的情况下附加到 url或在请求的情况下在 HTTP 正文中发送,"POST"即:行、页面、sidx、sord

For example if your table have a column with the index 'Col1'as the current sort column and rowNum: 20then your url will be appended with baseUrl?rows=20&page=1&sidx=Col1&sord=asc. Your server side coding should modify your query for data so that it is to be having ORDER BY (Col1 datafield in the table) ascand rowNum from 1 to 20.

例如,如果您的表有一列将索引'Col1'作为当前排序列,rowNum: 20那么您的 url 将附加baseUrl?rows=20&page=1&sidx=Col1&sord=asc. 您的服务器端编码应该修改您的数据查询,以便它具有ORDER BY (Col1 datafield in the table) ascrowNum from 1 to 20

If you have done as stated above and it is not working, you should verify your server code.

如果您已按照上述方法进行操作但仍无法正常工作,则应验证您的服务器代码。