How to add dynamically rows using ajax return type

2019-01-29 11:22发布

问题:

Step 1 : Default list of data populate in table.

Step 2 : after every 30 min once i have check using polling ajax method DB and append new list with old list.

Am not able to append first and sorting also not working.

ajax polling bind the data working but append in last row.

Please help me.

table code is below

$(document).ready(function () {
    jQuery("#list5").jqGrid({
        url: 'server.php?q=2',
        datatype: "json",
        colNames: ['Inv No', 'Date', 'Client', 'Amount', 'Tax', 'Total', 'Notes'],
        colModel: [{
            name: 'id',
            index: 'id',
            width: 55
        }, {
            name: 'invdate',
            index: 'invdate',
            width: 90
        }, {
            name: 'name',
            index: 'name',
            width: 100
        }, {
            name: 'amount',
            index: 'amount',
            width: 80,
            align: "right"
        }, {
            name: 'tax',
            index: 'tax',
            width: 80,
            align: "right"
        }, {
            name: 'total',
            index: 'total',
            width: 80,
            align: "right"
        }, {
            name: 'note',
            index: 'note',
            width: 150,
            sortable: false
        }],
        rowNum: 10,
        rowList: [10, 20, 30],
        pager: '#pager5',
        sortname: 'name',
        autoencode: true,
        loadonce: true,
        sortable: true,
        viewrecords: true,
        sortorder: "desc",
        jsonReader: {
            repeatitems: false,
            id: "ID"
        },
        multiselect: false,
        subGrid: false,

        caption: "Simple data manipulation",
        editurl: "someurl.php"
    }).navGrid("#pager5", {
        edit: false,
        add: false,
        del: false
    });
});

Poll ajax method is below

function poll() {

    var pollOutputJson;
    $.ajax({

        type: "POST",
        url: server.php ? q = 5,
        contentType : "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        cache: false,
        success: function (data) {
            pollOutputJson = data;
            var samGrid = jQuery("#list5");
            var su = samGrid.jqGrid('addRowData', 0, pollOutputJson);
            samGrid.setGridParam({
                rowNum: 15
            }).trigger("reloadGrid");
        },
        error: function (x, e) {
            alert("error occur");
        }
    });
    setTimeout((function (param) {
        return function () {
            poll();
        };
    })(), 180000);
}   

回答1:

First of all you need define the rowid of input data. The grid have the option jsonReader: {repeatitems: false, id: "ID"} and the column having name: 'id'. It means that every item of input data have to have unique "ID" property and should have additional "id" property. It seems strange.

Seconds, if you add new row using addRowData method you should use rowid as the first parameter. In your case the rowid will be specified by "ID" property of input data. So you should use something like data.ID as the first parameter of addRowData method. The code which you posted don't contains any clear description of the response from URL "server.php?q=5". If the input data is one item of data then the code should be samGrid.jqGrid("addRowData", data.ID, data). On the other side if data is array of items having "ID" as the property which specify the rowid then you should use samGrid.jqGrid("addRowData", "ID", data) to add the multiple rows.

The next problem which you have to solve is validation of rowid duplicates. Let us "server.php?q=5" returns one item to simplify the situation at the beginning. Is it possible that the item with the same ID property already exist in the grid? In the case you have to use setRowData instead of addRowData to modify/replace existing row instead of adding row and getting id duplicates which is not allowed in HTML.

One more problem in your question. You wrote that you don't want to append the data as the last row. On the other side you wrote that you want to have sorted data. So the position of the added data should depend on contain of name column (you use sortname: 'name' option).

Probably the most simple way to implement autorefresh of data by replacing all data in the grid. In the way the possible merge (modification of existing data) will be done on the server and the server could just return the full set of current data. Because you use loadonce: true then datatype of grid will be change to "local" after the first loading from the server and so you can work with the grid like with the grid having local data. It means the data parameter with array of items exist in the grid. by usage of

var intData = $("#list5").jqGrid("getGridParam", "data");

you get the reference to internal array with the data. Using

success: function (data) {
    var $mygrid = $("#list5"),
        allGridParams = $mygrid.jqGrid("getGridParam");
    allGridParams.data = data;
    $mygrid.trigger("reloadGrid", [{current: true}]);
}

Because $("#list5").jqGrid("getGridParam") represent the reference to all internal parameters of jqGrid the line allGridParams.data = data; replace old internal data to another array of items. The next line reload local grid. It means that the data will be sorted by sortname and the first page of the size specified by rowNum will be displayed. The option {current: true} of reloadGrid will try to select the same row after reloading which was selected.

Of cause you have to fix syntax error in your code (the line url: server.php ? q = 5, should be replacted to url: "server.php?q=5",) and you have to move the lines

setTimeout((function (param) {
    return function () {
        poll();
    };
})(), 180000);

out of body of the poll function.