簡體   English   中英

內聯編輯后如何將數據發送到服務器?

[英]How to send the data to the server after inline editing?

我正在使用jQgrid Free( 4.15.2版 ),並且需要添加內聯編輯行的功能,這根本不是問題,因為它很容易設置。 這是我正在使用的代碼:

$.jgrid = $.jgrid || {};
$.jgrid.no_legacy_api = true;
$.jgrid.useJSON = true;

$(function () {
    "use strict";

    var $grid = $("#list"),
        pagerSelector = "#pager",
        customAddButton = function (options) {
            $grid.jqGrid('navButtonAdd', pagerSelector, options);
            $grid.jqGrid('navButtonAdd', '#' + $grid[0].id + "_toppager", options);
        };

    $.fn.fmatter.customActionsFormatter = function (cellValue, options, rowData) {
        return '<a href="#" title="Delete selected row"><span class="fa fa-fw fa-trash-o delete_row" data-id="' + rowData.Id + '"></span></a>';
    };

    $grid.jqGrid({
        url: '/ajax/plans_to_forms/get_all',
        datatype: "json",
        colNames: ["", "Id", "Form #", "Form", "Plan", "Class", "Drug"],
        colModel: [
            {name: "act", formatter: "customActionsFormatter", width: 20, search: false},
            {name: "Id", jsonmap: "Id", key: true, hidden: true},
            {name: "FormId", align: 'center', fixed: true, frozen: true, resizable: false, width: 100},
            {name: "FormName", width: 300},
            {name: "PlanName", width: 300},
            {name: "DrugGroupName", width: 300},
            {name: "DrugName", width: 300}
        ],
        cmTemplate: {autoResizable: true, editable: true},
        iconSet: "fontAwesome",
        rowNum: 25,
        guiStyle: "bootstrap",
        autoResizing: {compact: true},
        rowList: [25, 50, 100, "10000:All"],
        viewrecords: true,
        autoencode: true,
        sortable: true,
        pager: pagerSelector,
        toppager: true,
        cloneToTop: true,
        hoverrows: true,
        multiselect: true,
        multiPageSelection: true,
        rownumbers: true,
        sortname: "Id",
        sortorder: "desc",
        loadonce: true,
        autowidth: true,
        autoresizeOnLoad: true,
        forceClientSorting: true,
        shrinkToFit: true,
        navOptions: {
            edit: false,
            add: false,
            del: false,
            search: false
        },
        inlineEditing: {keys: true, defaultFocusField: "DrugGroupName", focusField: "DrugGroupName"},
        onSelectRow: function (rowid, status, e) {
            var $self = $(this), savedRow = $self.jqGrid("getGridParam", "savedRow");

            if (savedRow.length > 0 && savedRow[0].id !== rowid) {
                $self.jqGrid("restoreRow", savedRow[0].id);
            }

            $self.jqGrid("editRow", rowid, {focusField: e.target});
        }
    }).jqGrid('navGrid', pagerSelector, {
        search: false,
        edit: false,
        add: false,
        del: false,
        refresh: true,
        cloneToTop: true
    }).jqGrid("filterToolbar", {
        stringResult: true, searchOnEnter: false, defaultSearch: 'cn'
    }).jqGrid("gridResize").jqGrid('setFrozenColumns');

    customAddButton({
        caption: 'Delete selected',
        buttonicon: 'fa-trash-o',
        title: "Delete all selected rows",
        onClickButton: function () {
            var rowIds = $("#list").jqGrid('getGridParam', 'selarrrow');

            if (rowIds.length > 0) {
                delete_all_link_modal.modal();
                delete_all_link_modal.attr('data-link-ids', rowIds);
            } else {
                alert('You must select at least one item.');
            }
        }
    });
});

以下行啟用內聯編輯:

inlineEditing: {keys: true, defaultFocusField: "DrugGroupName", focusField: "DrugGroupName"}

我的問題在哪里? 我只需要編輯DrugGroupName列,上面的行就可以使整行可編輯,這使我DrugGroupName以下問題:

  • 可以僅編輯給定的一組列而不是所有列嗎? -我在 這里檢查文檔 但找不到任何有用的信息

  • 我單擊任何其他位置或按ENTER鍵,是否可以將數據發送到服務器? -我想避免額外點擊保存圖標。

更新:我已經找到第一個問題的答案。 我只需要在定義colModel時使列不可編輯。 例如:

colModel: [
    {name: "act", formatter: "customActionsFormatter", width: 20, search: false},
    {name: "Id", jsonmap: "Id", key: true, hidden: true},
    {name: "FormId", align: 'center', fixed: true, frozen: true, resizable: false, width: 100, editable: false},
    {name: "FormName", width: 300, editable: false},
    {name: "PlanName", width: 300, editable: false},
    {
        name: "DrugGroupName",
        width: 300,
        edittype: "select",
        editoptions: {
            generateValue: true,
            selectFilled: function (options) {
                setTimeout(function () {
                    $(options.elem).select2({
                        width: "100%"
                    });
                }, 0);
            }
        },
        stype: "select", searchoptions: {
            sopt: ["eq", "ne"],
            generateValue: true,
            noFilterText: "Any",
            selectFilled: function (options) {
                $(options.elem).select2({
                    width: "100%"
                });
            }
        }
    },
    {name: "DrugName", width: 300, editable: false}
]

這樣,我將DrugGroupName強制為唯一可編輯的。

我認為您的代碼有很多小問題。 我准備了演示https://jsfiddle.net/OlegKi/rmo2370r/19/ ,該示例應該可以解決大多數問題,並演示select2的用法和免費jqGrid的某些功能。

第一個小問題是使用正確的rowid。 您使用當前隱藏的列

{name: "Id", jsonmap: "Id", key: true, hidden: true}

這是使用jqGrid的用戶的典型誤解。 Rowid將另存為行的id屬性( <tr>元素)。 圖片 人們無需將案例信息作為隱藏的<td>元素放置在網格內。 可以使用以下jqGrid選項代替它

prmNames: { id: "Id" },
jsonReader: { id: "Id" },

代替。 選項jsonReader.id通知jqGrid在填充網格期間從何處獲取rowid,而prmNames.id提供在編輯網格期間的ID名稱。

要在JSFiddle中填充jqGrid,可以使用Echo服務:

url: '/echo/json/',
datatype: 'json',
mtype: 'POST', // required for '/echo/json/'
postData: {
    json: JSON.stringify(mydata)
},

對URL /echo/json/的請求將mydata作為響應。 可以使用Chrome / IE / Firefox開發人員工具的“網絡”標簽詳細檢查HTTP流量。

同樣可以使用

editurl: '/echo/json/',
formDeleting: {
    url: '/echo/json/',
    ...
}

用於內聯編輯和表單刪除。

接下來的變化。 我在autoResizing添加了resetWidthOrg: true屬性:

autoResizing: {
    compact: true,
    resetWidthOrg: true
}

結合使用autoresizeOnLoad: true更改了工作的autowidth: true的結果。 您可以看到,所有列的寬度都比以前更好地基於列的內容。 請參閱問題以獲取更多詳細信息。

customActionsFormatter的目標。 我將其替換為標准格式化程序操作

{ name: "act", template: "actions" }

免費的jqGrid允許根據需要非常容易地自定義動作按鈕。 有關更多詳細信息,請參見答案Wiki文章

您使用的舊代碼

cmTemplate: {
  autoResizable: true,
  editable: true
}

並在大多數列中設置editable: false 取而代之的是,您只需要從cmTemplate刪除editable: true ,僅在需要編輯的一列中添加editable: true ,並在cmTemplate包含colModel最常用的其他設置:

cmTemplate: {
    width: 300,
    autoResizable: true
}

許多其他代碼也可以簡化。 例如,請參見onSelectRow的修改后的代碼。

要自定義刪除對話框,可以使用以下設置:

formDeleting: {
    url: '/echo/json/', // '/ajax/plans_to_forms/delete/' in final solution
    width: 320,
    caption: 'Delete Plan to Form Link',
    msg: 'Are you sure you want to delete this link?',
    beforeShowForm: function ($form) {
        var rowids = $form.find("#DelData>td").data("rowids");
            console.log(rowids);
            if (rowids.length > 1) {
            $form.find("td.delmsg")
                    .html('Are you sure you want to delete all the selected form links?');
            }
    }
}

刪除將數據Id=20622,20626oper=del發送到服務器( formDeleting.url )。 如果需要,可以使用serializeDelData將數據轉換為JSON。

要在編輯過程中將更多數據從列發送到服務器,可以在某些列中添加editable: "hidden" 我在演示的FormId列中添加了該屬性,並且在編輯過程中發送到服務器的數據看起來像

{"FormId":"3393","DrugGroupName":"Some other value","oper":"edit","Id":"20620"}

要針對服務器的其他Ajax請求填充<select>數據,需要使用editoptions.dataUrl 我在演示中添加了editoptions.postData來僅模擬對服務器的實際請求:

editoptions: {
    dataUrl: "/echo/json/",
    postData: {
        json: JSON.stringify([
                "Non-Specialty Medications",
                "General Pharmacy Authorization",
                "Some other value"
            ])
        },
        buildSelect: function (data) {
            var select = "<select>", i;

            for (i = 0; i < data.length; i++) {
                select += "<option value='" + String(data[i]).replace(/\'/g, "&#39;") +
                            "'>" + $.jgrid.htmlEncode(data[i]) + "</option>"
            }
            return select + "</select>";
        },
        selectFilled: function(options) {
            var $self = $(this);

            setTimeout(function() {
                $(options.elem).select2({
                    width: "100%"
                }).on('select2:select', function (e) { 
                    // save the data on selection
                    $self.jqGrid("saveRow", options.rowid);
                });
            }, 0);
        }
    },
    stype: "select",
    searchoptions: {
        sopt: ["eq", "ne"],
        generateValue: true,
        noFilterText: "Any",
        selectFilled: function(options) {
            $(options.elem).select2({
                width: "100%"
            });
        }
    }
}

上面對dataUrl請求返回JSON字符串[ "Non-Specialty Medications", "General Pharmacy Authorization", "Some other value" ]並且buildSelect使用<select>包含所有<options>將數據轉換為HTML片段。 結果<select>將被轉換為selectFilled回調內部的select2 contril。 最后代碼使用

ajaxSelectOptions: {
    type: "POST",
    dataType: "json"
}

選項將Ajax請求的參數更改為dataUrl 演示https://jsfiddle.net/OlegKi/rmo2370r/19/包含一些其他小的更改,例如刪除不需要的空pager div和pager: true的用法,就像您已經使用toppager: true 這是又一個功能,我在免費的jqGrid分支中實現了該功能,以簡化jqGrid的使用。

暫無
暫無

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

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