簡體   English   中英

在免費jqGrid中添加/編輯/刪除行

[英]Add/edit/delete a row in free jqGrid

我正在使用免費的jqGrid 4.12.1。 我想在網格中添加,編輯和刪除行,並希望為每個操作進行服務器端調用。 我添加了如下的editurl和'actions'格式化程序,

 {
  name: "actions",
  width: 100,
  formatter: "actions",
  formatoptions: {
      keys: true,
      editOptions: {},
      addOptions: {},
      delOptions: {}
  }       
  }

我在下面添加“ inlineNav”,

$("#itemList").jqGrid('inlineNav',"#itemListPager", 
         {
            edit: true,
            add: true,
            del: true,
            search: true,
            searchtext: "Search",
            addtext: "Add",
            edittext: "Edit",
            deltext: "Delete"
        },
        {  
            closeOnEscape: true, //Closes the popup on pressing escape key
            reloadAfterSubmit: true,
            drag: true,
            url: "${pageContext.request.contextPath}/billing/saveItem",
            errorfunc: function (rowId, resp) {
                alert(resp);
            },
            afterSubmit: function (response, postdata) {
                if (response.responseText == "") {

                    $(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after edit
                    return [true, '']
                }
                else {
                    $(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after edit
                    return [false, response.responseText]//Captures and displays the response text on th Edit window
                }
            },
            editData: {
                EmpId: function () {
                    var sel_id = $('#itemList').jqGrid('getGridParam', 'selrow');
                    var value = $('#itemList').jqGrid('getCell', sel_id, '_id');
                    return value;
                }
            }
        },
        {
            closeAfterAdd: true, //Closes the add window after add
            url: "${pageContext.request.contextPath}/billing/saveItem",
            afterSubmit: function (response, postdata) {
                if (response.responseText == "") {

                    $(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')//Reloads the grid after Add
                    return [true, '']
                }
                else {
                    $(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')//Reloads the grid after Add
                    return [false, response.responseText]
                }
            }
        },
        {   //DELETE
            closeOnEscape: true,
            closeAfterDelete: true,
            reloadAfterSubmit: true,              
            url: "${pageContext.request.contextPath}/billing/saveItem",
            drag: true,
            afterSubmit: function (response, postdata) {
                if (response.responseText == "") {

                    $("#itemList").trigger("reloadGrid", [{ current: true}]);
                    return [false, response.responseText]
                }
                else {
                    $(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
                    return [true, response.responseText]
                }
            },
            delData: {
                EmpId: function () {
                    var sel_id = $('#itemList').jqGrid('getGridParam', 'selrow');
                    var value = $('#itemList').jqGrid('getCell', sel_id, '_id');
                    return value;
                }
            }
        },
        {//SEARCH
            closeOnEscape: true
        }       
        );

上面添加的'inlineNav'無效,因為在添加新行或刪除現有行時不會進行服務器端調用。 僅在編輯的情況下才進行服務器端調用,並且該調用也不會通過上面的“ inlineNav”代碼發生。 因為即使我刪除了“ inlineNav”代碼,服務器端調用仍然是對“ editurl”進行的。 因此,我該如何在添加/編輯/刪除行上進行服務器端調用,以及如何將參數傳遞給這些調用。 如果有人能指出我在某處的工作示例,我將不勝感激。 謝謝

更新: -

我刪除了“動作”格式化程序,並修改了代碼,使其看起來如下所示,

<script type="text/javascript">

var dataGrid = $('#itemList');
var firstClick = true;
    $(document).ready(function () {
        $('#action').click(function () {
            if (!firstClick) {
                $("#itemList").setGridParam({datatype:'json'}).trigger("reloadGrid");
            }   
            firstClick = false;
        $("#itemList").jqGrid({
            url: "${pageContext.request.contextPath}/billing/medicines",
            datatype: "json",
            //styleUI : 'Bootstrap',
            mtype: "POST",
            autowidth: true,
            shrinkToFit: true,
            sortname: "Id",
            sortorder: "asc",
            loadBeforeSend: function(jqXHR) {
                 jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val());
            },
            postData: {
            },
            loadError: function (jqXHR, textStatus, errorThrown) {
                alert('HTTP status code: ' + jqXHR.status + '\n' +
                      'textStatus: ' + textStatus + '\n' +
                      'errorThrown: ' + errorThrown);
                alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText); 
            },
            colNames: ["Id", "Item Type", "Item Code", "Unit", "Stock", "Batch No.", "Expiry Date", "Quantity Per Unit", "Price"],
            colModel: [
                { name: "itemId", width: 35, align: "left", sorttype:"int", search: false},
                { name: "itemType", width: 100, align: "left",  editable: true},
                { name: "itemCode", width: 120, align: "left",  editable: true},
                { name: "unit", width: 70, align: "left", search: false,  editable: true},
                { name: "availableQuantity", width: 55, align: "left", search: false, formatter: "number",  editable: true},
                { name: "batchNumber", width: 80, align: "left", search: false,  editable: true},
                { name: "expiryDate", width: 80, align: "left", search: false, sorttype: "date",  editable: true, formatoptions: {srcformat:'d/m/Y', newformat:'d/m/Y'}},
                { name: "quantityPerUnit", width: 80, align: "left", search: false, formatter: "number",  editable: true},
                { name: "price", width: 55, align: "left", search: false, formatter: "number",  editable: true}
            ],
            pager: "#itemListPager",
            rowNum: 50,
            rowList: [50, 100, 150, 200],
            rownumbers: true,
            rownumWidth: 25,
            sortname: "id",
            sortorder: "desc",
            viewrecords: true,
            height: '100%',
            loadonce: true,
            //gridview: true,
            autoencode: true,
            editurl: "${pageContext.request.contextPath}/billing/saveItem",
            caption: "Item List",
            ondblClickRow: function(rowId){}
        }).navGrid('#itemListPager',{add:false,edit:false,del:true});
        $("#itemList").jqGrid('filterToolbar', {autoSearch: true, stringResult: true, searchOnEnter: false, defaultSearch: 'cn'});
        $("#itemList").jqGrid('gridResize', { minWidth: 450, minHeight: 150 });

        var saveparameters = {
                "successfunc" : null,
                "url" : "${pageContext.request.contextPath}/billing/saveItem",
                    "extraparam" : {},
                "aftersavefunc" : null,
                "errorfunc": null,
                "afterrestorefunc" : null,
                "restoreAfterError" : true,
                "mtype" : "POST"
            };

        var editparameters = {
                "keys" : false,
                "oneditfunc" : null,
                "successfunc" : null,
                "url" : "${pageContext.request.contextPath}/billing/editItem",
                    "extraparam" : {},
                "aftersavefunc" : null,
                "errorfunc": null,
                "afterrestorefunc" : null,
                "restoreAfterError" : true,
                "mtype" : "POST"
            };

        var parameters = { 
                   edit: true,
                   editicon: "ui-icon-pencil",
                   add: true,
                   addicon:"ui-icon-plus",
                   save: true,
                   saveicon:"ui-icon-disk",
                   cancel: true,
                   cancelicon:"ui-icon-cancel",
                   addParams : saveparameters,
                   editParams : editparameters
                };
        $("#itemList").jqGrid('inlineNav',"#itemListPager", parameters);

    });
});
</script> 

樣本json dada是這樣的,

[
{"itemDetailId":1,"itemId":1,"itemType":"Medicine","itemCode":"Aler-Dryl","itemDesc":"Aler-Dryl","batchNumber":"batch1","expiryDate":"18/02/2017","unit":"tablet","subUnit":"tablet","availableQuantity":120.0,"quantityPerUnit":60.0,"price":122.0},
{"itemDetailId":2,"itemId":2,"itemType":"Medicine","itemCode":"Benadryl","itemDesc":"Benadryl","batchNumber":"batch1","expiryDate":"18/02/2017","unit":"ml","subUnit":"ml","availableQuantity":60.0,"quantityPerUnit":120.0,"price":90.0}
]

現在,分別在編輯和添加行時調用在editparameters和saveparameters中指定的url。 請建議以上方法是否是一種好的方法。 同樣,我們如何在將編輯或保存數據發布到服務器之前設置請求標頭。 而且我找不到類似於deleteparameters的東西,類似於editparameters和saveparameters,所以我可以使用delete特定參數。

更新2:-

在使用以下代碼在添加/編輯行上調用服務器端代碼之前,我可以成功設置一個請求標頭,

 $.ajaxSetup({
            beforeSend: function (jqXHR, settings) {                     
               jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val());
          }});

更新3:-
按照以下Oleg的建議清理代碼。 但是在嚴格模式下,我現在遇到JS錯誤-“未捕獲的ReferenceError:未定義saveparameters”

<script type="text/javascript">
$(document).ready(function () {
    "use strict";
    var dataGrid = $('#itemList');
    var firstClick = true;
    $('#action').click(function () {
        if (!firstClick) {
            $("#itemList").setGridParam({datatype:'json'}).trigger("reloadGrid");
        }   
        firstClick = false;
    $("#itemList").jqGrid({
        url: "${pageContext.request.contextPath}/billing/medicines",
        datatype: "json",
        mtype: "POST",
        autowidth: true,
        loadBeforeSend: function(jqXHR) {
             jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val());
        },
        colNames: ["Id", "Item Type", "Item Code", "Unit", "Stock", "Batch No.", "Expiry Date", "Quantity Per Unit", "Price"],
        colModel: [
            { name: "itemId", width: 35, align: "left", sorttype:"int", search: false, editable: false, key: true},
            { name: "itemType", width: 100, align: "left"},
            { name: "itemCode", width: 120, align: "left"},
            { name: "unit", width: 70, align: "left", search: false},
            { name: "availableQuantity", width: 55, align: "left", search: false, formatter: "number",},
            { name: "batchNumber", width: 80, align: "left", search: false},
            { name: "expiryDate", width: 80, align: "left", search: false, sorttype: "date", formatoptions: {srcformat:'d/m/Y', newformat:'d/m/Y'}},
            { name: "quantityPerUnit", width: 80, align: "left", search: false, formatter: "number"},
            { name: "price", width: 55, align: "left", search: false, formatter: "number"}
        ],
        cmTemplate: {editable: true},
        pager: true,
        rowNum: 50,
        rowList: [50, 100, 150, 200],
        rownumbers: true,
        rownumWidth: 25,
        sortname: "itemType",
        sortorder: "asc",
        forceClientSorting: true,
        viewrecords: true,
        height: '100%',
        loadonce: true,
        //gridview: true,
        autoencode: true,
        editurl: "${pageContext.request.contextPath}/billing/saveItem",
        caption: "Item List"
        //ajaxRowOptions: { beforeSend: myTokenSetting }, loadBeforeSend: myTokenSetting where var myTokenSetting = function(jqXHR) { jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val()); }
    }).navGrid({add:false,edit:false,del:true});
    $("#itemList").jqGrid('filterToolbar', {autoSearch: true, stringResult: true, searchOnEnter: false, defaultSearch: 'cn'});
    $("#itemList").jqGrid('gridResize', { minWidth: 450, minHeight: 150 });

    var saveparameters = {
            "successfunc" : null,
            "url" : "${pageContext.request.contextPath}/billing/saveItem",
             "extraparam" : {},
            "aftersavefunc" : null,
            "errorfunc": null,
            "afterrestorefunc" : null,
            "restoreAfterError" : true,
            "mtype" : "POST"
        };

    var editparameters = {
            "keys" : false,
            "oneditfunc" : null,
            "successfunc" : null,
            "url" : "${pageContext.request.contextPath}/billing/editItem",
             "extraparam" : {},
            "aftersavefunc" : null,
            "errorfunc": null,
            "afterrestorefunc" : null,
            "restoreAfterError" : true,
            "mtype" : "POST"
        };

    var parameters = { 
               edit: true,
               editicon: "ui-icon-pencil",
               add: true,
               addicon:"ui-icon-plus",
               save: true,
               saveicon:"ui-icon-disk",
               cancel: true,
               cancelicon:"ui-icon-cancel",
               addParams : saveparameters,
               editParams : editparameters
            };
    $("#itemList").jqGrid('inlineNav',parameters);

    $.ajaxSetup({
        beforeSend: function (jqXHR, settings) {
           alert('Before Row Send');         
           jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val());
      }});

    });
});
</script>

您應該檢查inlineNav的選項,以發現您使用了絕對錯誤的選項:

jQuery("#grid_id").jqGrid('inlineNav', pagerid, parameters);

parameters的形式

{ 
    edit: true,
    editicon: "ui-icon-pencil",
    add: true,
    addicon: "ui-icon-plus",
    save: true,
    saveicon: "ui-icon-disk",
    cancel: true,
    cancelicon: "ui-icon-cancel",
    addParams: {useFormatter : false},
    editParams: {}
}

您使用另一種方法navGrid的選項

jQuery("#grid_id").jqGrid('navGrid', '#gridpager', {parameters},
    prmEdit, prmAdd, prmDel, prmSearch, prmView);

允許使用表單編輯

你寫你想要同時使用formater: "actions" inlineNav . Thus you would have to provide some options of inline editing twice. I would recommend you to read [the wiki article](https://github.com/free-jqgrid/jqGrid/wiki/New-style-of-usage-options-of-internal-methods). It describes the problems with the usage of form editing using . Thus you would have to provide some options of inline editing twice. I would recommend you to read [the wiki article](https://github.com/free-jqgrid/jqGrid/wiki/New-style-of-usage-options-of-internal-methods). It describes the problems with the usage of form editing using . Thus you would have to provide some options of inline editing twice. I would recommend you to read [the wiki article](https://github.com/free-jqgrid/jqGrid/wiki/New-style-of-usage-options-of-internal-methods). It describes the problems with the usage of form editing using格式化程序“ actions” and navGrid together. The usage of inline editing have very close problems. You will have to provide . Thus you would have to provide some options of inline editing twice. I would recommend you to read [the wiki article](https://github.com/free-jqgrid/jqGrid/wiki/New-style-of-usage-options-of-internal-methods). It describes the problems with the usage of form editing using together. The usage of inline editing have very close problems. You will have to provide together. The usage of inline editing have very close problems. You will have to provide together. The usage of inline editing have very close problems. You will have to provide inlineNav的addParams and editParams properties of and the corresponding options of formatter and the corresponding options of :“ actions”`(請參見此處 )。 為了使代碼更具可讀性和簡單性,免費的jqGrid提供了另一種形式的編輯選項。

您可以指定所有內嵌編輯選項里面的inlineEditing jqGrid的的選擇,額外的特定選項inlineNav方法(如果需要)在navOptionsinlineNavOptions ,在刪除操作的選項formDeleting等。 此外, reloadGrid還具有fromServer: true選項,以恢復您使用的datatype"json""jsonp""xml" ,...)的原始值。 您可以使用表單編輯或formDeleting reloadGridOptions: { fromServer: true }選項強制從服務器重新加載。

而且,您現有的代碼包含很多帶有_idEmpId可疑部分。 我強烈建議您提供用於填充網格的JSON輸入數據格式示例。 如果要使用EmpId作為rowid的名稱,為什么要改用_id 代碼片段像

EmpId: function () {
    var sel_id = $('#itemList').jqGrid('getGridParam', 'selrow');
    var value = $('#itemList').jqGrid('getCell', sel_id, '_id');
    return value;
}

顯示當前的rowid似乎是錯誤的,並且_id列包含正確的信息,您需要以EmpId的名稱作為rowid。

例如,您可以使用prmNames: { id: "EmpId"}並將key: true添加到_id列。 該物業key: true_id會通知的jqGrid使用的值從列_id為ROWID和prmNames: { id: "EmpId"}將重命名默認的id在編輯使用屬性和Delete EmpId 因此,jqGrid將在“刪除”和“編輯”操作期間將帶有_id列中值的EmpId參數自動發送到服務器。

也許您也可以從網格中刪除不需要的列_id (至少在隱藏該列的情況下),但是我需要查看jqGrid的輸入數據以說出可以使用的jqGrid的確切選項。

我確信您可以使用免費的jqGrid選項實質上減少現有代碼並使其更具可讀性,但是您必須仔細檢查現有代碼。 我建議您首先使用正確的rowid並消除所使用的所有隱藏列。 免費的jqGrid提供additionalProperties功能,結構非常接近的結構colModel ,但輸入相應的數據屬性將被保存在本地數據僅供參考,不放在桌上的DOM。 我可以更清楚地解釋一下,如果您要發布現有的colModeljsonReader和從服務器返回的JSON響應示例(1-2行帶有偽數據的數據就足夠了)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM