我正在尝试为添加到jqGrid的新行分配唯一的ID。我使用免费的jqGrid 4.11.0,它是服务器端的java rest服务,而数据库是MS SQL。
inlineEditing: { ajaxSaveOptions: { contentType: "application/json" }, serializeSaveData: function (postData) { var idArray = grid.getCol('id'); var count = 0; var k = 1; while(postData.id.search('jqg') != '-1'){ for(var i =0 ; i<idArray.length;i++){ if(k == idArray[i]){ count++; } if(count == 0){ postData.id = k ; break; } } k++; } return JSON.stringify(postData); } }
我注意到jqGrid给出的默认ID是jqg +一个数字。关于如何制作唯一未在任何数据库记录中使用的唯一ID的任何建议?我应该从服务器端执行此操作还是可以在jqGrid代码中进行?
在晚上的某个时间点,此代码可以正常工作,并继续为所有新行赋予id 7(即使它应该一直在增加)。进行一些更改后(想不起来有什么更改),每次我单击“保存”以将新行提交到服务器时,页面冻结,chrome建议我终止该过程。
请让我知道什么以及是否应该添加更多信息。
编辑1:
$(function () { var grid = $('#grid'), checkboxEditOptionEvents = [ {type : 'click', data: {'Yes': 'Yes'}, fn: function (e, id) { var checkboxCol = grid.getCol('sefDepartament'), ids = grid.jqGrid('getDataIDs'), numberOfCheckedBoxes = [], k; for (k = 0; k < ids.length; k++) { if(checkboxCol[k] == 'Yes'){ numberOfCheckedBoxes.push(checkboxCol[k]); if (numberOfCheckedBoxes.length == 1){ alert('Please deselect the other checked box first'); $(this).prop("checked",false); numberOfCheckedBoxes = 0; } } } }}]; var experienceFunction = function(cellvalue, options ,rowObject){ var joinYearVar = rowObject.joinYear, YY = joinYearVar.slice(0,4), MM = joinYearVar.slice(5,7), DD= joinYearVar.slice(8,11); return moment("\"" +YY+MM+DD+"\"" , "YYYYMMDD").fromNow(); }; var checkboxFormatFunc = function(cellvalue, options ,rowObject){ if(cellvalue == 'Yes'){ return 'Yes'; } return 'No'; }; var afterSaveFunction = function(id){ var prenumeVar = grid.getCell(id, 'prenume').trim(), numeVar = grid.getCell(id,'nume').trim(), usernameVar = numeVar +'.'+ prenumeVar, emailVar = usernameVar + '@test.com'; usernameVar =usernameVar.replace(/\s/g , '').trim(); emailVar = emailVar.replace(/\s/g , ''); grid.setCell(id, 'username', usernameVar); grid.setCell(id, 'email', emailVar); }; var colModelSettings = [ {name:'id', label:'id',key: true,hidden: true, width:10,sorttype:'number',editable: false}, {name:'nume',label:'Nume',width:90, align: 'center',editable:true,searchoptions: {sopt: ['eq','bw','ew','cn']}, editrules:{required:true}, editoptions: {defaultValue: ' '},formatter: 'text'}, {name:'prenume',label:'Prenume',width:100,editable:true,searchoptions: {sopt: ['eq','bw','ew','cn']},align: 'center',editrules:{required:true},editoptions: {defaultValue: ' '},formatter: 'text'}, {name:'username',label:'Username',searchoptions: {sopt: ['eq','bw','ew','cn']},width:125,align: 'center' }, {name:'email',label:'Email',width:135,searchoptions: {sopt: ['eq','bw','ew','cn']},align: 'center'}, {name:'sefDepartament',label:'Sef Departament',width:90,editable:true,align: 'center', stype:"select", searchoptions:{sopt: ['eq','ne'],value: "Yes:Yes;No:No"},formatter: checkboxFormatFunc,edittype:'checkbox',editoptions: { dataEvents: checkboxEditOptionEvents,value:'Yes:No', defaultValue: 'No' }}, {name:'position',label:'Position',editable:true,stype: 'select',formatter: 'select',searchoptions: {sopt: ['eq','ne'],value: ' : ;position 1:position 1;position 2:position 2;position 3:position 3;position 4:position 4;position 5:position 5'}, align: 'center',edittype:'select',editoptions:{defaultvalue: 'P0: ',value: ' : ;position 1:position 1;position 2:position 2;position 3:position 3;position 4:position 4;position 5:position 5'},width: 75}, {name:'joinYear',label:'Join Year',formatter:'date', formatoptions: {newformat:'d-m-Y'}, datefmt: 'dd-mm-yyyy', editable:true,searchtype: 'datepicker',align: 'center',width: 70, searchoptions:{dateFormat:'dd-mm-yy',dataInit: function (elem){ $(elem).datepicker({ showButtonPanel: true, dateFormat: 'yy-mm-dd'});},sopt: ['eq','ne']}, editoptions:{size:20,defaultValue: ' ',dataInit: function (elem) { $(elem).datepicker({ showButtonPanel: true, dateFormat: 'dd-mm-yy'}); }}}, {name:'experience', label:'Experience', formatter: experienceFunction, searchoptions:{sopt: ['eq','bw','ew','cn']}, editable:'hidden', editoptions:{defaultValue: ' '},align: 'center',width: 60}, {name:'actiuni',label: 'Actiuni',formatter: 'actions', formatoptions: {afterSave:afterSaveFunction},editable: false,sortable: false,search: false,width: 20 } ]; grid.jqGrid({ pager: '#pager', url: "/RestWithDatabaseConnection/rest/fetchData", editurl:'/RestWithDatabaseConnection/rest/update', datatype: "json", height: 250, viewrecords: true, scrollOffset:0, sortorder: 'asc', caption:'Employee List' , autowidth: true, colModel: colModelSettings, beforeSelectRow : function(id){ var idsArray = grid.jqGrid('getDataIDs'); var i; for(i=0;i<idsArray.length;i++){ if($('#'+idsArray[i]).is('[editable="1"]') ){ grid.editRow(idsArray[i],true); return false; } } return true; }, inlineEditing: { ajaxSaveOptions: { contentType: "application/json" }, serializeSaveData: function (postData) { var idArray = grid.getCol('id'); var count = 0; var k = 1; while(postData.id.search('jqg') != '-1'){ for(var i =0 ; i<idArray.length;i++){ if(k == idArray[i]){ count++; } if(count == 0){ postData.id = k ; break; } } k++; } return JSON.stringify(postData); } } }); grid.jqGrid('navGrid', '#pager', {edit:false, add:false, delete:true, save:false, cancel:false, search:true, searchtext: 'Search', refresh:true}, {},{},{ url: '/RestWithDatabaseConnection/rest/delete', mtype: 'DELETE', reloadAfterSubmit: true, ajaxDelOptions: { contentType: "application/json", }, serializeDelData: function(postdata) { return JSON.stringify(postdata); }},{},{},{},{} ); grid.jqGrid('inlineNav','#pager', { edit:true, edittext: 'Edit', save:true, savetext: 'Save', add:true, cancel: true, canceltext: 'Cancel', cancelicon: 'ui-icon-cancel', addicon:'ui-icon-plus', addtext: 'Add', addedrow: 'last', addParams: { position: 'last', addRowParams: { aftersavefunc : afterSaveFunction, keys: true, } }, editParams:{ url: '/RestWithDatabaseConnection/rest/update', mtype : "POST", keys: true, aftersavefunc : afterSaveFunction, } })})
Edit2-服务器对fetchData的响应:
[{"id":"3","nume":"Aladin","prenume":"Zoro","username":"Aladin.Zoro","email":"Aladin.Zoro@test.com","sefDepartament":"Yes","position":"position 4","joinYear":"2015-11-08","experience":"2 months"}, {"id":"2","nume":"Harap","prenume":"Alb","username":"Harap.Alb","email":"Harap.Alb@test.com","sefDepartament":"No","position":"position 1","joinYear":"2016-01-03","experience":"9 days "}, {"id":"4","nume":"Don","prenume":"Homa","username":"Don.Homa","email":"Don.Homa@test.com","sefDepartament":"No","position":"position 4","joinYear":"2015-09-06","experience":"4 months"}, {"id":"5","nume":"Dorel","prenume":"Gigel","username":"Dorel.Gigel","email":"Dorel.Gigel@test.com","sefDepartament":"No","position":"position 4","joinYear":"2016-01-10","experience":"2 days"}, {"id":"1","nume":"Ivan","prenume":"Stefan","username":"Ivan.Stefan","email":"Ivan.Stefan@test.com","sefDepartament":"No","position":"position 2","joinYear":"2016-01-10","experience":"2 days"}]
以下是一些建议,可以解决您的主要问题并改善您发布的JavaScript代码。
首先,新的rowid产生 局部 需要本地编辑场景。如果将数据保存在数据库的后端,则应 在服务器上 生成新的rowid 。典型的实现包括在 每个 表中进行PRIMARY KEY定义。它使ID唯一且固定。删除某一行并创建新行将永远不会被解释为对旧行的编辑,因为新行将始终获得新的ID,而该ID从未在表中使用过。int IDENTITY __
PRIMARY KEY
int IDENTITY
要利用在 服务器端 生成的ID的优势,有两个主要选择:
aftersavefunc
$("#" + rowid).attr("id", newRowid);
id
setCell
首选是最简单的方法,我建议您首先实施它。仅当网格的重新加载不能满足用户的需求时(他们又接连添加了许多行),您才应该编写一些代码并实现第二种方案。
您当前的代码inlineNav用于通过内联编辑实现的“添加”和“编辑”操作,以及navGrid通过表单编辑实现的“删除”操作的方法。reloadAfterSubmit: true默认情况下,表单编辑(包括删除)使用选项。这意味着url: "/RestWithDatabaseConnection/rest/fetchData"在删除每一行之后,将从服务器(从中)重新加载网格。您可以通过替换afterSaveFunction以下内容来解决主要问题:
inlineNav
navGrid
reloadAfterSubmit: true
url: "/RestWithDatabaseConnection/rest/fetchData"
afterSaveFunction
var afterSaveFunction = function () { $(this).trigger("reloadGrid", [{current: true, fromServer: true}]); };
选项current重装之后保持当前的选择和选项fromServer: true都感觉只有在情况下,如果你使用loadonce: true的选项还。您只需使用导航选项栏上的刷新/重新加载按钮,就可以强制使用reloadGridOptions: {fromServer: true}选项 从服务器navGrid重新加载数据。如果没有太多需要在网格中显示的数据(例如少于1000行),则建议采取这种行为。 __
current
fromServer: true
loadonce: true
reloadGridOptions: {fromServer: true}
一些更常见的建议可以改善您的代码:
您可以考虑通过指定值来height: "auto"代替height: 250和管理网格的最大高度rowNum。scrollOffset: 0在这种情况下,将不需要该选项。
height: "auto"
height: 250
rowNum
scrollOffset: 0
从服务器返回的数据格式看起来像这样,因此您 没有实现服务器端的分页,排序和过滤 。您应该使用loadonce: true和forceClientSorting: true选项。该loadonce: true运筹学的jqGrid保存 所有 从服务器内部本地返回的数据data参数。您可以随时通过用法访问数组$('#grid').jqGrid("getGridParam", "data")。值rowNum(默认值为20)将用于 本地 分页。在sortname与sortorder将被用于 当地的 排序。然后,您将使用搜索对话框(由添加navGrid)或过滤器工具栏(由添加filterToolbar)来查找 本地 搜索/过滤。它简化了服务器代码,从用户的角度提高了网格的性能,并简化了服务器和客户端之间的接口。您可以在服务器上使用经典的RESTful接口,而无需任何扩展。
forceClientSorting: true
data
$('#grid').jqGrid("getGridParam", "data")
sortname
sortorder
filterToolbar
另一个说明:建议您删除不需要的隐藏id列(name:'id', label:'id', key: true, hidden: true, ...)。关于rowid的信息将保存在idrows(<tr>元素)的属性中,不需要<td>在每行的隐藏元素中保留重复信息。
name:'id', label:'id', key: true, hidden: true, ...
<tr>
<td>
您的代码还有很多其他部分,可以进行改进。例如,您在服务器端使用的DELETE操作似乎很奇怪。您使用mtype: 'DELETE',但是将请求 正文 中已删除行的ID 发送到服务器,而不是将其附加到URL。对应于标准,HTTP DELETE不应该包含 body 。您可以使用jqGrid选项formDeleting指定所有Delete选项,还可以将url参数定义为函数:
mtype: 'DELETE'
formDeleting
url
formDeleting: { mtype: "DELETE", url: function (rowid) { return "/RestWithDatabaseConnection/rest/delete/" + rowid; }, ajaxDelOptions: { contentType: "application/json" }, serializeDelData: function () { return ""; } }
您需要原因修改服务器代码,/RestWithDatabaseConnection/rest/delete/以使用相同的通信协议并从URL中获取已删除的ID。
/RestWithDatabaseConnection/rest/delete/
您可以使用navOptionsfree jqGrid的参数来指定以下选项navGrid:
navOptions
navOptions: { edit: false, add: false }
(searchtext: 'Search'以及您使用的其他选项似乎具有默认值,因此我将其删除了)。
searchtext: 'Search'
为了更接近REST标准,可以使用HTTP PUT操作进行行编辑,并使用HTTP POST添加新行。您应该为后端的两个操作实现 不同的 入口点。您/RestWithDatabaseConnection/rest/update已经使用过,可以实现/RestWithDatabaseConnection/rest/create添加新行。inlineEditing例如,您可以使用以下更改来实现方案:
/RestWithDatabaseConnection/rest/update
/RestWithDatabaseConnection/rest/create
inlineEditing
inlineNavOptions: { add: true, edit: true }, inlineEditing: { url: function (id, editOrAdd) { return "/RestWithDatabaseConnection/rest/" + (editOrAdd === "edit" ? "update" : "create"); }, mtype: function (editOrAdd) { return editOrAdd === "edit" ? "PUT" : "POST"; }, keys: true, serializeSaveData: function (postData) { return JSON.stringify(dataToSend); }, aftersavefunc: function () { $(this).trigger("reloadGrid", [{current: true, fromServer: true}]); }, addParams: { addRowParams: { position: "last", serializeSaveData: function (postData) { var dataToSend = $.extend({}, postData); // don't send any id in case of creating new row // or to send `0`: delete dataToSend.id; // or dataToSend.id = 0; return JSON.stringify(dataToSend); } } } }