使用 jqGrid 的内联编辑和 RESTful url?

发布于 2024-12-03 21:56:13 字数 859 浏览 0 评论 0原文

我正在使用 jqGrid,并且希望能够使用其内置编辑功能来进行 ajax 调用来添加/编辑/删除。我们的 API 使用 RESTful 动词和 url,如下所示:

verb     url               action
--------------------------------------------------------------
GET      /api/widgets      get all widgets (to populate grid)
POST     /api/widgets      create new widget
PUT      /api/widgets/1    update widget 1
DELETE   /api/widgets/1    delete widget 1

是否可以在这些限制下使用内置的 ajax 处理,或者我是否必须使用本地数据(如概述 此处 & 此处)并自己管理ajax调用?如果可能的话,我应该在网格上设置哪些属性?

ajaxRowOptions 看起来很有希望,但是文档< /a> 关于如何使用它有点薄弱。)

I'm using jqGrid and would like to be able to use its built-in editing functions to make ajax calls to add/edit/delete. Our API uses RESTful verbs and urls like so:

verb     url               action
--------------------------------------------------------------
GET      /api/widgets      get all widgets (to populate grid)
POST     /api/widgets      create new widget
PUT      /api/widgets/1    update widget 1
DELETE   /api/widgets/1    delete widget 1

Is it possible to use the built-in ajax handling with these restrictions, or do I have to use local data (as outlined here & here) and manage the ajax calls myself? If it is possible, what properties do I set on the grid?

(ajaxRowOptions looks promising, but the documentation is a bit thin on how to use it.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

日裸衫吸 2024-12-10 21:56:13

Add 表单中默认使用 POST

为 RESTfull 后端定制 jqGrid 的主要思想可以在 旧答案

如果您使用导航器工具栏的“删除”按钮,则在表单编辑中使用“删除”。请查看此处此处。因此,您应该使用以下设置:

$("#grid").jqGrid('navGrid', '#pager',
    {edit: false, add: false, search: false}, {}, {},
    { // Delete parameters
        mtype: "DELETE",
        serializeDelData: function () {
            return ""; // don't send and body for the HTTP DELETE
        },
        onclickSubmit: function (params, postdata) {
            params.url = '/api/widgets/' + encodeURIComponent(postdata);
        }
    });

我在上面的示例中使用 encodeURIComponent 函数确保 id 是否有一些特殊字符(例如空格)将被编码,以便服务器部分自动接收原始(解码)数据。您可能需要为向服务器发送删除请求期间使用的 $.ajax 调用设置一些附加设置。您可以使用 ajaxDelOptions 属性。

您可以将上述设置设为默认设置。您可以按照以下方式执行此操作

$.extend($.jgrid.del, {
    mtype: "DELETE",
    serializeDelData: function () {
        return ""; // don't send and body for the HTTP DELETE
    },
    onclickSubmit: function (params, postdata) {
        params.url = '/api/widgets/' + encodeURIComponent(postdata);
    }
});

上面示例中的方法 onclickSubmit 可用于编辑操作(在表单编辑的情况下),将 URL 动态修改为 /api/widgets /1。在许多情况下,在上述形式中使用 onclickSubmit 是不可能的,因为需要使用不同的基本 url ('/api/widgets') 和不同的网格。在可以使用的情况下

$.extend($.jgrid.del, {
    mtype: "DELETE",
    serializeDelData: function () {
        return ""; // don't send and body for the HTTP DELETE
    },
    onclickSubmit: function (params, postdata) {
        params.url += '/' + encodeURIComponent(postdata);
    }
});

,那么 navGrid 的使用应该明确设置 url

$("#grid").jqGrid('navGrid', '#pager',
    {edit: false, add: false, search: false}, {}, {},
    { // Delete parameters
        url: '/api/widgets'
    });


要在内联编辑中使用“PUT”,您可以设置以下默认 jqGrid 设置:

$.extend($.jgrid.defaults, {
    ajaxRowOptions: { contentType: "application/json", type: "PUT", async: true },
    serializeRowData: function (data) {
        var propertyName, propertyValue, dataToSend = {};
        for (propertyName in data) {
            if (data.hasOwnProperty(propertyName)) {
                propertyValue = data[propertyName];
                if ($.isFunction(propertyValue)) {
                    dataToSend[propertyName] = propertyValue();
                } else {
                    dataToSend[propertyName] = propertyValue;
                }
            }
        }
        return JSON.stringify(dataToSend);
    }
});

一般情况下不需要设置 contentType: "application/json",但某些服务器技术可能需要它。上例中的回调函数 serializeRowData 以 JSON 形式发送数据。 RESTfull 不需要它,但它很常见。函数 JSON.stringify 是在最新的 Web 浏览器中本机实现的,但为了确保它在旧浏览器中工作,您应该包含 json2.js 在您的页面上。

serializeRowData 的代码可能非常简单

serializeRowData: function (data) {
    return JSON.stringify(data);
}

,但我使用上面的代码能够使用方法 editRow (参见 此处< /a> 和问题描述此处)。

editRow 中 RESTfull URL(如 /api/widgets/1)的用法非常简单:

$(this).editRow(rowid, true, null, null, '/api/widgets/' + encodeURIComponent(rowid));

要在表单编辑时使用它,您应该

grid.navGrid('#pager', {},
    { mtype: "PUT", url: '/api/widgets' });

$.extend($.jgrid.edit, {
    ajaxEditOptions: { contentType: "application/json" }, // can be not required
    onclickSubmit: function (params, postdata) {
        params.url += '/' + encodeURIComponent(postdata.list_id);
    }
});

使用 需要注意的是,要从 onclickSubmit 内部的 postdata 获取 id,需要使用 postdata.list_id 而不是postdata.id,其中'list'是网格的ID。为了能够使用不同的网格()ID,可以使用new非标准参数。例如,在下面的代码中,我使用 myGridId:

var myEditUrlBase = '/api/widgets';
grid.navGrid('#pager', {},
    { mtype: "PUT", url: myEditUrlBase, myGridId: 'list' },
    { // Add options
        url: myEditUrlBase },
    { // Delete options
        url: myEditUrlBase });

并将默认设置定义为

$.extend($.jgrid.del, {
    mtype: "DELETE",
    serializeDelData: function () {
        return ""; // don't send and body for the HTTP DELETE
    },
    onclickSubmit: function (params, postdata) {
        params.url += '/' + encodeURIComponent(postdata);
    }
});

$.extend($.jgrid.edit, {
    ajaxEditOptions: { contentType: "application/json" }, // can be not required
    onclickSubmit: function (params, postdata) {
        params.url += '/' + encodeURIComponent(postdata[params.myGridId + '_id']);
    }
});

In case of the use of 格式化程序:'actions' (参见 此处此处)进行内联或表单编辑(或混合)您可以使用与前面描述的相同的技术,但使用 editOptionsdelOptions 格式选项转发所有需要的编辑/删除选项。

您的最后一个问题是使用 GET 作为 /api/widgets。经典的 RESTfull 服务将仅返回所有项目的数组作为 /api/widgets 上的响应。因此,您应该只使用 loadonce: truejsonReader ,它们使用方法而不是属性(请参阅此处此处)。

loadonce: true,
jsonReader: {
    repeatitems: false,
    root: function (obj) { return obj; },
    page: function () { return 1; },
    total: function () { return 1; },
    records: function (obj) { return obj.length; }
}

您应该以某种方式包含哪些项目属性可以用作网格行的 id 的信息。该 ID 在页面上必须唯一。如果您的数据没有 id,我建议您将其用作

id: function () { return $.jgrid.randId(); }

附加的 jsonReader 方法,因为默认情况下,当前版本的 jqGrid 使用顺序整数(“1”、“2”、“3”、.. .) 作为行 ID。如果同一页面上至少有两个网格,则会出现问题。

如果“GET”返回的数据大小超过 100 行,我建议您最好使用服务器端分页。这意味着您将在服务器部分添加一个附加方法,该方法支持服务器端数据排序和分页。我建议您阅读答案,其中我描述了原因 输入数据的标准格式不是 RESTfull 项目数组,并且还具有 pagetotalrecords。对于经典的 RESTful 设计来说,新方法可能并不陌生,但本机甚至 SQL 代码中的排序和分页数据可以显着提高最终用户的总体性能。如果标准 jqGrid 输入参数的名称(pagerowssidxsord),您可以使用 < code>prmNames jqGrid 参数在那里重命名。

The usage of POST in Add form is by default.

The main idea for customizing jqGrid for RESTfull backend you can find in the old answer.

To use 'DELETE' in form editing if you use the Delete button of the navigator toolbar. Look at here or here. So you should use about the following settings:

$("#grid").jqGrid('navGrid', '#pager',
    {edit: false, add: false, search: false}, {}, {},
    { // Delete parameters
        mtype: "DELETE",
        serializeDelData: function () {
            return ""; // don't send and body for the HTTP DELETE
        },
        onclickSubmit: function (params, postdata) {
            params.url = '/api/widgets/' + encodeURIComponent(postdata);
        }
    });

I use in the example above the encodeURIComponent function to be sure that if the id will have some special characters (spaces for example) if will be encoded so that the server part automatically received the original (decoded) data. Probably you will need to set some additional settings for the $.ajax call used during sending Delete request to the server. You can use for it ajaxDelOptions property.

You can make the above settings as your default settings. You can do this with respect of the following

$.extend($.jgrid.del, {
    mtype: "DELETE",
    serializeDelData: function () {
        return ""; // don't send and body for the HTTP DELETE
    },
    onclickSubmit: function (params, postdata) {
        params.url = '/api/widgets/' + encodeURIComponent(postdata);
    }
});

The method onclickSubmit from the example above can be used for the Edit operations (in case of form editing) to modify the URL dynamically to /api/widgets/1. In many cases the usage of onclickSubmit in the above form is not possible because one need to use different base urls ('/api/widgets') different grids. In the case one can use

$.extend($.jgrid.del, {
    mtype: "DELETE",
    serializeDelData: function () {
        return ""; // don't send and body for the HTTP DELETE
    },
    onclickSubmit: function (params, postdata) {
        params.url += '/' + encodeURIComponent(postdata);
    }
});

Then the usage of navGrid should be with explicit setting of url

$("#grid").jqGrid('navGrid', '#pager',
    {edit: false, add: false, search: false}, {}, {},
    { // Delete parameters
        url: '/api/widgets'
    });

and
To use 'PUT' in inline editing you can set the following default jqGrid settings:

$.extend($.jgrid.defaults, {
    ajaxRowOptions: { contentType: "application/json", type: "PUT", async: true },
    serializeRowData: function (data) {
        var propertyName, propertyValue, dataToSend = {};
        for (propertyName in data) {
            if (data.hasOwnProperty(propertyName)) {
                propertyValue = data[propertyName];
                if ($.isFunction(propertyValue)) {
                    dataToSend[propertyName] = propertyValue();
                } else {
                    dataToSend[propertyName] = propertyValue;
                }
            }
        }
        return JSON.stringify(dataToSend);
    }
});

The setting contentType: "application/json" is not required in general, but it could be required for some server technologies. The callback function serializeRowData from the example above sent the data as JSON. It is not required for RESTfull, but it's very common. The function JSON.stringify is native implemented in the most recent web browsers, but to be sure that it work in old browsers to you should include json2.js on your page.

The code of serializeRowData could be very simple like

serializeRowData: function (data) {
    return JSON.stringify(data);
}

but I use above code to be able to use functions inside of the extraparam of the method editRow (see here and the problem description here).

The usage of the RESTfull URL (like /api/widgets/1) in the editRow is very simple:

$(this).editRow(rowid, true, null, null, '/api/widgets/' + encodeURIComponent(rowid));

To use it in case of the form editing you should use

grid.navGrid('#pager', {},
    { mtype: "PUT", url: '/api/widgets' });

and

$.extend($.jgrid.edit, {
    ajaxEditOptions: { contentType: "application/json" }, // can be not required
    onclickSubmit: function (params, postdata) {
        params.url += '/' + encodeURIComponent(postdata.list_id);
    }
});

It is important to remark that to get id from the postdata inside of onclickSubmit and need use postdata.list_id instead of postdata.id, where 'list' is the id of the grid. To be able to use different grid (<table>) ids one can use new non-standard parameter. For example, in the code below I use myGridId:

var myEditUrlBase = '/api/widgets';
grid.navGrid('#pager', {},
    { mtype: "PUT", url: myEditUrlBase, myGridId: 'list' },
    { // Add options
        url: myEditUrlBase },
    { // Delete options
        url: myEditUrlBase });

and the default setting defined as

$.extend($.jgrid.del, {
    mtype: "DELETE",
    serializeDelData: function () {
        return ""; // don't send and body for the HTTP DELETE
    },
    onclickSubmit: function (params, postdata) {
        params.url += '/' + encodeURIComponent(postdata);
    }
});

$.extend($.jgrid.edit, {
    ajaxEditOptions: { contentType: "application/json" }, // can be not required
    onclickSubmit: function (params, postdata) {
        params.url += '/' + encodeURIComponent(postdata[params.myGridId + '_id']);
    }
});

In case of the usage of formatter:'actions' (see here and here) with inline or form editing (or a mix) you can use the same technique as described before, but forward all needed Edit/Delete option using editOptions and delOptions formatoptions.

The last your question was the usage of GET as /api/widgets. The classical RESTfull services will returns just array of all items as the response on /api/widgets. So you should just use loadonce: true and jsonReader which used methods instead of properties (See here and here).

loadonce: true,
jsonReader: {
    repeatitems: false,
    root: function (obj) { return obj; },
    page: function () { return 1; },
    total: function () { return 1; },
    records: function (obj) { return obj.length; }
}

You should in some way include information which item property can be used as the id of grid rows. The id must be unique on the page. It your data has no id I would recommend you to use

id: function () { return $.jgrid.randId(); }

as an additional jsonReader method because per default the current version of jqGrid use sequential integers ("1", "2", "3", ...) as the row ids. In case of having at least two grids on the same page it will follow to the problems.

If the size of the data returned by 'GET' are more as 100 rows I would you recommend better to use server side paging. It means that you will add an additional method in the server part which support server side sorting and paging of data. I recommend you to read the answer where I described why the standard format of the input data are not RESTfull array of items and has page, total and records additionally. The new method will be probably not strange for the classical RESTful design, but the sorting and paging data in native or even SQL code can improve the total performance from the side of enduser dramatically. If the names of the standard jqGrid input parameters (page, rows, sidx and sord) you can use prmNames jqGrid parameter to rename there.

故人爱我别走 2024-12-10 21:56:13

另请查看这个优秀的通用教程,了解如何为 RESTful URL 设置 jqGrid 这里,其中还包括相应的 Spring MVC 服务器部分的外观。

Also check out this excellent general tutorial for how to set-up jqGrid for RESTful URL's here, which also includes how the corresponding Spring MVC server portion would look.

三岁铭 2024-12-10 21:56:13

我设法通过实现 beforeSubmitCell 事件处理程序来实现它:

beforeSubmitCell: function(rowId) {

            jQuery("#grid-HumanResource-table").jqGrid(
                'setGridParam',
                {
                    cellurl: s.getBaseModule().config.baseAPIUrl + "humanResource/" + rowId
                }
            );
        },

我正在使用 jqGrid 4.6 版本。

I have managed to achieve it by implementing beforeSubmitCell event handler:

beforeSubmitCell: function(rowId) {

            jQuery("#grid-HumanResource-table").jqGrid(
                'setGridParam',
                {
                    cellurl: s.getBaseModule().config.baseAPIUrl + "humanResource/" + rowId
                }
            );
        },

I am using jqGrid 4.6 version.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文