本文介绍了将 jqGrid 的内联编辑与 RESTful url 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

动词 url 动作--------------------------------------------------------------GET/api/widgets 获取所有小部件(填充网格)POST/api/widgets 创建新的小部件PUT/api/widgets/1 更新小部件 1DELETE/api/widgets/1 删除小部件 1

是否可以使用具有这些限制的内置 ajax 处理,或者我必须使用本地数据(如概述 这里 & 这里)和管理ajax 调用自己?如果可能,我在网格上设置什么属性?

(ajaxRowOptions 看起来很有希望,但 文档关于如何使用它有点薄.)

解决方案

POST在Add表单中的用法是默认的.

您可以在 旧答案.

如果您使用导航工具栏的删除按钮,则在表单编辑中使用删除".查看这里这里.所以你应该使用以下设置:

$("#grid").jqGrid('navGrid', '#pager',{假,添加:假,搜索:假},{},{},{//删除参数mtype:删除",序列化德尔数据:函数(){返回 "";//不要为 HTTP DELETE 发送和正文},onclickSubmit:函数(参数,postdata){params.url = '/api/widgets/' + encodeURIComponent(postdata);}});

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

您可以将上述设置设为您的默认设置.您可以针对以下内容执行此操作

$.extend($.jgrid.del, {mtype:删除",序列化德尔数据:函数(){返回 "";//不要为 HTTP DELETE 发送和正文},onclickSubmit:函数(参数,postdata){params.url = '/api/widgets/' + encodeURIComponent(postdata);}});

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

$.extend($.jgrid.del, {mtype:删除",序列化德尔数据:函数(){返回 "";//不要为 HTTP DELETE 发送和正文},onclickSubmit:函数(参数,postdata){params.url += '/' + encodeURIComponent(postdata);}});

那么navGrid的使用要明确设置url

$("#grid").jqGrid('navGrid', '#pager',{假,添加:假,搜索:假},{},{},{//删除参数网址:'/api/widgets'});

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

$.extend($.jgrid.defaults, {ajaxRowOptions: { contentType: "application/json", type: "PUT", async: true },serializeRowData:函数(数据){var 属性名,属性值,数据发送 = {};for(数据中的属性名称){if (data.hasOwnProperty(propertyName)) {属性值 = 数据 [属性名称];if ($.isFunction(propertyValue)) {dataToSend[propertyName] = propertyValue();} 别的 {dataToSend[propertyName] = propertyValue;}}}返回 JSON.stringify(dataToSend);}});

contentType: "application/json" 设置通常不是必需的,但某些服务器技术可能需要它.上例中的回调函数 serializeRowData 将数据作为 JSON 发送.RESTfull 不需要它,但它很常见.JSON.stringify 函数是在最新的网络浏览器中本地实现的,但要确保它在旧浏览器中工作,您应该包括 json2.js 在您的页面上.

serializeRowData的代码可以很简单,比如

serializeRowData: 函数(数据){返回 JSON.stringify(data);}

但我使用上面的代码能够使用 (参见 here 和问题描述 这里).

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" },//可以不需要onclickSubmit:函数(参数,postdata){params.url += '/' + encodeURIComponent(postdata.list_id);}});

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

var myEditUrlBase = '/api/widgets';grid.navGrid('#pager', {},{ mtype: "PUT", url: myEditUrlBase, myGridId: 'list' },{//添加选项网址:myEditUrlBase },{//删除选项网址:myEditUrlBase });

默认设置定义为

$.extend($.jgrid.del, {mtype:删除",序列化德尔数据:函数(){返回 "";//不要为 HTTP DELETE 发送和正文},onclickSubmit:函数(参数,postdata){params.url += '/' + encodeURIComponent(postdata);}});$.extend($.jgrid.edit, {ajaxEditOptions: { contentType: "application/json" },//可以不需要onclickSubmit:函数(参数,postdata){params.url += '/' + encodeURIComponent(postdata[params.myGridId + '_id']);}});

如果使用 formatter:'actions'(请参阅此处这里) 使用内联或表单编辑(或混合),您可以使用与前面描述的相同的技术,但转发所有需要的使用 editOptionsdelOptions 格式选项编辑/删除选项.

您的最后一个问题是 GET 作为 /api/widgets 的用法.经典的 RESTfull 服务将仅返回所有项目的数组作为对 /api/widgets 的响应.所以你应该只使用 loadonce: truejsonReader 使用方法而不是属性(参见 这里这里).

loadonce: true,jsonReader:{重复项:错误,根:函数(obj){返回obj;},页面:函数(){返回1;},总计:函数(){返回1;},记录:函数(obj){返回obj.length;}}

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

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

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

如果GET"返回的数据大小超过 100 行,我建议您最好使用服务器端分页.这意味着您将在服务器部分添加一个 additional 方法,该方法支持服务器端数据的排序和分页.我建议您阅读我描述的答案为什么em> 输入数据的标准格式不是 RESTfull 数组,另外还有 pagetotalrecords.新方法对于经典的 RESTful 设计可能并不陌生,但是 native 甚至 SQL 代码中的排序和分页数据可以从最终用户方面显着提高整体性能.如果标准 jqGrid 输入参数的名称(pagerowssidxsord)可以使用 prmNames jqGrid 参数在那里重命名.

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.)

解决方案

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'
    });

andTo 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.

这篇关于将 jqGrid 的内联编辑与 RESTful url 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 19:55