Load local JSON data in jQgrid without AddJsonRows

Brecht picture Brecht · Jul 26, 2011 · Viewed 52.7k times · Source

I'm using the method addJsonRows to add local data to a jQgrid. As this method disables the sorting I need another solution. One restriction: I can't set the url and fetch the data from the server because the data was passed through another component.

Underneath snippet enlightens the case. The commented line shows the restriction, I replaced it by defining a local variable to have a test case.

<script type="text/javascript" language="javascript">
    function loadPackageGrid() {
    // Get package grid data from hidden input.
    // var data = eval("("+$("#qsmId").find(".qsm-data-packages").first().val()+")");
        var data =  {
            "page": "1",
            "records": "2",
            "rows": [
                { "id": "83123a", "PackageCode": "83123a" },
                { "id": "83566a", "PackageCode": "83566a" }
            ]
        };

        $("#packages")[0].addJSONData(data);
    };

    $(document).ready(function() {
        $("#packages").jqGrid({
            colModel: [
                { name: 'PackageCode', index: 'PackageCode', width: "110" },
                { name: 'Name', index: 'Name', width: "300" }
            ],
            pager: $('#packagePager'),
            datatype: "local",
            rowNum: 10000,
            viewrecords: true,
            caption: "Packages",
            height: 150,
            pgbuttons: false,
            loadonce: true
        });
    });
</script>

I wonder how I could do this in an other (better) way to keep the sorting feature. I tried something with the data option, without result.

Answer

Oleg picture Oleg · Jul 26, 2011

I suppose that the same question is interesting for other persons. So +1 from me for the question.

You can solve the problem in at least two ways. The first one you can use datatype: "jsonstring" and datastr: data. In the case you need to add additional parameter jsonReader: { repeatitems: false }.

The second way is to use datatype: "local" and data: data.rows. In the case the localReader will be used to read the data from the data.rows array. The default localReader can read the data.

The corresponding demos are here and here.

I modified a little your data: filled "Name" column and included the third item in the input data.

Now you can use local paging, sorting and filtering/searching of the data. I included a little more code to demonstrate the features. Below you find the code of one from the demos:

$(document).ready(function () {
    'use strict';
    var data = {
            "page": "1",
            "records": "3",
            "rows": [
                { "id": "83123a", Name: "Name 1", "PackageCode": "83123a" },
                { "id": "83432a", Name: "Name 3", "PackageCode": "83432a" },
                { "id": "83566a", Name: "Name 2", "PackageCode": "83566a" }
            ]
        },
        grid = $("#packages");

    grid.jqGrid({
        colModel: [
            { name: 'PackageCode', index: 'PackageCode', width: "110" },
            { name: 'Name', index: 'Name', width: "300" }
        ],
        pager: '#packagePager',
        datatype: "jsonstring",
        datastr: data,
        jsonReader: { repeatitems: false },
        rowNum: 2,
        viewrecords: true,
        caption: "Packages",
        height: "auto",
        ignoreCase: true
    });
    grid.jqGrid('navGrid', '#packagePager',
        { add: false, edit: false, del: false }, {}, {}, {},
        { multipleSearch: true, multipleGroup: true });
    grid.jqGrid('filterToolbar', { defaultSearch: 'cn', stringResult: true });
});

UPDATED: I decided to add more details about the differences between datatype: "jsonstring" and datatype: "local" scenarios because the old answer be read and voted by many readers.

I suggest to modify the above code a little to show better the differences. The fist code uses datatype: "jsonstring"

$(function () {
    "use strict";
    var data = [
            { id: "10", Name: "Name 1", PackageCode: "83123a", other: "x", subobject: { x: "a", y: "b", z: [1, 2, 3]} },
            { id: "20", Name: "Name 3", PackageCode: "83432a", other: "y", subobject: { x: "c", y: "d", z: [4, 5, 6]} },
            { id: "30", Name: "Name 2", PackageCode: "83566a", other: "z", subobject: { x: "e", y: "f", z: [7, 8, 9]} }
        ],
        $grid = $("#packages");

    $grid.jqGrid({
        data: data,
        datatype: "local",
        colModel: [
            { name: "PackageCode", width: 110 },
            { name: "Name", width: 300 }
        ],
        pager: "#packagePager",
        rowNum: 2,
        rowList: [1, 2, 10],
        viewrecords: true,
        rownumbers: true,
        caption: "Packages",
        height: "auto",
        sortname: "Name",
        autoencode: true,
        gridview: true,
        ignoreCase: true,
        onSelectRow: function (rowid) {
            var rowData = $(this).jqGrid("getLocalRow", rowid), str = "", p;
            for (p in rowData) {
                if (rowData.hasOwnProperty(p)) {
                    str += "propery \"" + p + "\" + have the value \"" + rowData[p] + "\n";
                }
            }
            alert("all properties of selected row having id=\"" + rowid + "\":\n\n" + str);
        }
    });
    $grid.jqGrid("navGrid", "#packagePager",
        { add: false, edit: false, del: false }, {}, {}, {},
        { multipleSearch: true, multipleGroup: true });
    $grid.jqGrid("filterToolbar", { defaultSearch: "cn", stringResult: true });
});

It displays (see the demo)

enter image description here

One can see unsorted items in the same order like input data. The items of input data will be saved in internal parameters data and _index. getLocalRow method used in onSelectRow shows that items of internal data contains only properties of input items which names corresponds to name property of some jqGrid columns. Additionally unneeded _id_ property will be added.

On the other side the next demo which uses datatype: "local" displays sorted data and all properties inclusive complex objects will be still saved in the internal data:

enter image description here

The code used in the last demo is included below:

$(function () {
    "use strict";
    var data = [
            { id: "10", Name: "Name 1", PackageCode: "83123a", other: "x", subobject: { x: "a", y: "b", z: [1, 2, 3]} },
            { id: "20", Name: "Name 3", PackageCode: "83432a", other: "y", subobject: { x: "c", y: "d", z: [4, 5, 6]} },
            { id: "30", Name: "Name 2", PackageCode: "83566a", other: "z", subobject: { x: "e", y: "f", z: [7, 8, 9]} }
        ],
        $grid = $("#packages");

    $grid.jqGrid({
        data: data,
        datatype: "local",
        colModel: [
            { name: "PackageCode", width: 110 },
            { name: "Name", width: 300 }
        ],
        pager: "#packagePager",
        rowNum: 2,
        rowList: [1, 2, 10],
        viewrecords: true,
        rownumbers: true,
        caption: "Packages",
        height: "auto",
        sortname: "Name",
        autoencode: true,
        gridview: true,
        ignoreCase: true,
        onSelectRow: function (rowid) {
            var rowData = $(this).jqGrid("getLocalRow", rowid), str = "", p;
            for (p in rowData) {
                if (rowData.hasOwnProperty(p)) {
                    str += "propery \"" + p + "\" + have the value \"" + rowData[p] + "\"\n";
                }
            }
            alert("all properties of selected row having id=\"" + rowid + "\":\n\n" + str);
        }
    });
    $grid.jqGrid("navGrid", "#packagePager",
        { add: false, edit: false, del: false }, {}, {}, {},
        { multipleSearch: true, multipleGroup: true });
    $grid.jqGrid("filterToolbar", { defaultSearch: "cn", stringResult: true });
});

So I would recommend to use datatype: "local" instead of datatype: "jsonstring". datatype: "jsonstring" could have some advantages only in some very specific scenarios.