如何将JSON数据加载到Jqgrid中

How to load the JSON data into the Jqgrid?

本文关键字:Jqgrid 加载 数据 JSON      更新时间:2023-09-26

我使用以下方式将数据加载到jqgrid中。我无法将json数据加载到jqgrid中。因此,我将json解析为类似mydata=json.parse(jsondata)的数组。然后,我使用数据类型"local"数组(mydata)绑定到jqgrid中。我的问题是如何将json数据绑定到jqcrid中

         $("#datagrid").jqGrid({
                    datatype: "local", 
                    data: mydata,
                    colNames:['companyid','company', 'price', 'Change','perchange','LastUpdated'],
                    colModel:[
                        {name:'companyid',index:'companyid', width:100,editable:true,editoptions:{size:10}},
                        {name:'company',index:'company', width:100,editable:true},
                        {name:'price',index:'price', width:100,editable:true,editoptions:{size:10}},
                        {name:'Change',index:'Change', width:100,editable:true,editoptions:{size:25}},
                        {name:'perchange',index:'perchange', width:100, align:"right",editable:true,editoptions:{size:10}},
                        {name:'LastUpdated',index:'LastUpdated', width:200, align:"right",editable:true,editoptions:{size:10}}
                    ],
                    rowNum:10,
                    rowList:[3,6],
                    loadonce: true,
                    pager: '#navGrid',
                    sortname: 'companyid',
                    sortorder: "asc", 
                    height: 210,
                    width:600,
                    onSelectRow: function(id)
                                 {
                                    getID = jQuery("#datagrid").jqGrid('getCell', id, 'companyid')
                                 },
                    viewrecords: true,
                    caption:"JQ GRID"
                }); 

JSON格式:

    [
        {
            "company": "test",
            "price": 98,
            "Change": 8,
            "perchange": 8,
            "LastUpdated": "2",
            "companyid": 2
        },
        {
            "company": "test123",
            "price": 1,
            "Change": 1,
            "perchange": 1,
            "LastUpdated": "1",
            "companyid": 3
        },
        {
            "company": "abc",
            "price": 1234,
            "Change": 123,
            "perchange": 1,
            "LastUpdated": "1",
            "companyid": 1
        }
    ]

首先,您需要在输入数据中定义行的id。每行的id属性(<tr>)将设置在相应的值中。因为您已经有companyid可以扮演这个角色,所以将key: true添加到colModel"companyid"列的属性中就足够了。

直接从服务器加载日期(包括从文件加载)的问题可以通过添加描述输入数据格式的jsonReader来解决。由于您使用loadonce: true,输入数据的totalrecordspage属性将被忽略,您可以使用以下简单形式的jsonReader

jsonReader: {repeatitems: false, root: function (obj) { return obj; }}

相应的演示在这里。

如果你需要从你发布的数据数组中加载数据,你的代码应该直接工作(参见另一个演示)。我想use在解析JSON数据时还有一些其他问题,但您没有发布相应的代码。

关于idkey: true的建议仍在进行中。您可以对第二种情况使用localReader: {id: "companyid"},也可以在jsonReader中使用相同的属性id: "companyid"。我个人更喜欢使用key: true,因为代码易于阅读,并且独立于所使用的阅读器。