jqGrid使用REST Api进行内联编辑(POST,PUT,DELETE http请求)

时间:2016-02-16 18:37:07

标签: jquery jqgrid

jqGrid版本: Guriddo jqGrid JS - v5.0.2

我的目标是什么? 我想创建一个内联的jqGrid。这里的Add将使用POST请求完成,Edit将使用PUT请求完成,删除将使用DELETE请求完成。

到目前为止我做了什么? 我可以使用RESTful webService进行内联编辑和删除(通过http PUT和DELETE请求)。

这是代码 -

var lastSel,
cancelEditing = function(myGrid) {
    var lrid;
    if (typeof lastSel !== "undefined") {
        myGrid.jqGrid('restoreRow', lastSel);
        lrid = $.jgrid.jqID(lastSel);
        $("tr#" + lrid + " div.ui-inline-edit, " + "tr#" + lrid + " div.ui-inline-del").show();
        $("tr#" + lrid + " div.ui-inline-save, " + "tr#" + lrid + " div.ui-inline-cancel").hide();
    }
};
$.extend($.jgrid.defaults, {
ajaxRowOptions: {
    contentType: "application/json",
    async: true,type:"PUT",
    beforeSend: function(jqXHR, settings) {
        jqXHR.setRequestHeader("Authorization", 'Basic ZHByZWdpc3RyYXI6MTIzNDU=');
        jqXHR.setRequestHeader("If-Match", '*');
    },
    complete: function(res, stat) {
        if (res.status == 200 || res.status == 204) {
            $("#jqGrid").trigger("reloadGrid");
        } else {
            return [false, res.responseText];
        }
    }
},
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);
}
});

var thisGrid = $("#jqGrid").jqGrid({
datatype: "json",
url: 'https://localhost/MyWebService/academic/classroom/all',
editurl: 'https://localhost/MyWebService/academic/classroom',
loadBeforeSend: function(jqXHR) {
    jqXHR.setRequestHeader("Authorization", 'Basic ZHByZWdpc3RyYXI6MTIzNDU=');
},
jsonReader: {
    repeatitems: false
},
colModel: [{
        label: 'Room Id',
        name: 'id',
        width: 10,
        hidden: true,
        key: true
    }, {
        label: 'Room Number',
        name: 'roomNo',
        editable: true,
        width: 100
    }, {
        label: "Edit Actions",
        name: "actions",
        width: 100,
        formatter: "actions",
        formatoptions: {
            keys: true,
            editOptions: {},
            addOptions: {
                mtype: 'POST'
            },
            delOptions: {
                mtype: 'DELETE',
                onclickSubmit: function(rp_ge) {
                    var selrow_id = thisGrid.getGridParam('selrow');
                    var rowdata = thisGrid.getRowData(selrow_id);
                    rp_ge.url = "https://localhost/MyWebService/academic/classroom" + '/' + selrow_id;
                },
                ajaxDelOptions: {
                    contentType: "application/json",
                    beforeSend: function(jqXHR) {
                        jqXHR.setRequestHeader("Authorization", 'Basic ZHByZWdpc3RyYXI6MTIzNDU=');
                    }
                },
                serializeDelData: function(postdata) {
                    return JSON.stringify(postdata);
                }
            },
            onEdit: function(id) {
                if (typeof(lastSel) !== "undefined" && id !== lastSel) {
                    cancelEditing(thisGrid);
                }
                lastSel = id;
                $("#jqGrid").setGridParam({
                    editurl: "https://localhost/MyWebService/academic/classroom/" + encodeURIComponent(id)
                });
            }

        }
    }
],
sortname: 'id',
loadonce: true,
autowidth: true,
pager: "#jqGridPager",
rownumbers: true,
height: 500,

rowList: [], // disable page size dropdown
pgbuttons: false, // disable page control like next, back button
pgtext: null,

ondblClickRow: function(id, ri, ci, e) {
    if (typeof(lastSel) !== "undefined" && id !== lastSel) {
        cancelEditing($(this));
    }
    lastSel = id;
    var lrid = $.jgrid.jqID(lastSel);
    if (!e) e = window.event; // get browser independent object
    var element = e.target || e.srcElement;


    $("#jqGrid").jqGrid('editRow', id, true, function() {
        var colModel = jQuery("#jqGrid").jqGrid('getGridParam', 'colModel');
        var colName = colModel[ci].name;
        var input = $('#' + id + '_' + colName);
        console.log(input)
        setTimeout(function() {
            input.get(0).focus();
        }, 300);
    }, null, "https://localhost/MyWebService/academic/classroom/" + encodeURIComponent(id));
    $("tr#" + lrid + " div.ui-inline-edit, " + "tr#" + lrid + " div.ui-inline-del").hide();
    $("tr#" + lrid + " div.ui-inline-save, " + "tr#" + lrid + " div.ui-inline-cancel").show();
}
});
var addOptions = {
keys: true,
type: "POST",
url: "https://localhost/MyWebService/academic/classroom/",
successfunc: function() {
    var $self = $(this);
    setTimeout(function() {
        $self.trigger("reloadGrid");
    }, 50);
    }
};
$("#jqGrid").jqGrid("inlineNav", "#jqGridPager", {
addParams: {
    position: "last",
    addRowParams: addOptions
    }
});

问题:当我尝试保存新创建的记录时,我得到了http请求类型PUT而不是POST。我知道它的原因。下面的代码负责 -

$.extend($.jgrid.defaults, {
    ajaxRowOptions: { contentType: "application/json", async: true,type:"PUT",

我无法覆盖此类型:" PUT"键入的设置:" POST"在创建新行时。

还有其他一些美容观察。我在随附的图像文件中提供了该评论。

enter image description here

修改1 这是我的更新代码:

  $.jgrid.defaults.responsive = true;
  $.jgrid.defaults.styleUI = 'Bootstrap';
  $.extend($.jgrid.inlineEdit, { restoreAfterError: false });

   var lastSel,
  cancelEditing = function(myGrid) {
    var lrid;
    if (typeof lastSel !== "undefined") {
      myGrid.jqGrid('restoreRow',lastSel);
      lrid = $.jgrid.jqID(lastSel);
      $("tr#" + lrid + " div.ui-inline-edit, " + "tr#" + lrid + " div.ui-inline-del").show();
      $("tr#" + lrid + " div.ui-inline-save, " + "tr#" + lrid + " div.ui-inline-cancel").hide();
    }
  };
  $.extend($.jgrid.defaults, {
    ajaxRowOptions: { contentType: "application/json", async: true,
      beforeSend: function (jqXHR, settings) {
        jqXHR.setRequestHeader("Authorization", 'Basic ZHByZWdpc3RyYXI6MTIzNDU=');
        jqXHR.setRequestHeader("If-Match", '*');
      },
      complete: function(res, stat) {
        if (res.status==200 || res.status==204) {
          $("#jqGrid").trigger("reloadGrid");
        } else {
          return [false, res.responseText ];
        }
      }
    },
    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);
    }
  });

  var thisGrid =$("#jqGrid").jqGrid({
    datatype: "json",
    url: 'https://localhost/ums-webservice-common/academic/classroom/all',
    editurl:'https://localhost/ums-webservice-common/academic/classroom',
    loadBeforeSend: function(jqXHR) {
      jqXHR.setRequestHeader("Authorization", 'Basic ZHByZWdpc3RyYXI6MTIzNDU=');
    },
    jsonReader: { repeatitems: false },
    colModel: [
      {
        label: 'Room Id',
        name: 'id',
        width: 10,
        hidden:true,
        key: true
      },
      {
        label: 'Room Number',
        name: 'roomNo',
        editable: true,
        width: 100
      },
      {
        label: 'Description',
        name: 'description',
        editable: true,
        width: 200
      },
      {
        label : 'Row',
        name: 'totalRow',
        width: 50,
        editable: true
      },
      {
        label: 'Column',
        name: 'totalColumn',
        width: 50,
        editable: true
      },
      {
        label: 'Capacity',
        name: 'capacity',
        width: 50,
        editable: true
      },
      {
        label: 'Room Type',
        name: 'roomType',
        editable: true,
        width: 100, align: 'center', formatter: 'select',
        edittype: 'select',
        editoptions: {
          value: '1:Theory;2:Sessional;0:Others',
          defaultValue: 'Theory'
        },
        stype: 'select',
        searchoptions: {
          sopt: ['eq', 'ne'],
          value: '1:Theory;2:Sessional;0:Others'
        }},


      {
        label: 'Dept./School',
        name: 'capacity',
        width: 100,
        editable: true
      },
      {
        label: 'Seat Plan',
        name: 'examSeatPlan',
        editable: true,
        width: 80, align: 'center', formatter: 'checkbox',
        edittype: 'checkbox', editoptions: {value: '1:0', defaultValue: '1'},
        stype: 'select',
        searchoptions: {
          sopt: ['eq', 'ne'],
          value: '1:Yes;0:No'
        }


      },
      {
        label: "Edit Actions",
        name: "actions",
        width: 100,
        formatter: "actions",
        formatoptions: {
          keys: true,
          editOptions: {
            mtype: 'PUT'
          },
          addOptions: {
            mtype: 'POST'
          },
          delOptions: {
            mtype: 'DELETE',
            onclickSubmit: function(rp_ge) {
              var selrow_id = thisGrid.getGridParam('selrow');
              var rowdata = thisGrid.getRowData(selrow_id);
              rp_ge.url = "https://localhost/ums-webservice-common/academic/classroom" + '/' + selrow_id ;
            },
            ajaxDelOptions: {
              contentType: "application/json",
              beforeSend: function(jqXHR) {
                jqXHR.setRequestHeader("Authorization", 'Basic ZHByZWdpc3RyYXI6MTIzNDU=');
              }
            },
            serializeDelData: function(postdata) {
              return JSON.stringify(postdata);
            }
          },
          onEdit: function (id) {
            if (typeof (lastSel) !== "undefined" && id !== lastSel) {
              cancelEditing(thisGrid);
            }
            lastSel = id;
            $("#jqGrid").setGridParam({ editurl: "https://localhost/ums-webservice-common/academic/classroom/" + encodeURIComponent(id)});
          }

        }
      }
    ],
    sortname: 'id',
    loadonce: true,
    autowidth: true,
    pager: "#jqGridPager",
    rownumbers: true,
    height:500,

    rowList: [],        // disable page size dropdown
    pgbuttons: false,     // disable page control like next, back button
    pgtext: null,

    ondblClickRow: function(id, ri, ci,e) {
      if (typeof (lastSel) !== "undefined" && id !== lastSel) {
        cancelEditing($(this));
      }
      lastSel = id;
      var lrid = $.jgrid.jqID(lastSel);
      if (!e) e = window.event; // get browser independent object
      var element = e.target || e.srcElement;


      $("#jqGrid").jqGrid('editRow',id,true,function() {
        var colModel = jQuery("#jqGrid").jqGrid ('getGridParam', 'colModel');
        var colName = colModel[ci].name;
        var input = $('#' + id + '_' + colName);
        console.log(input)
        setTimeout(function(){  input.get(0).focus(); }, 300);
      },null,"https://localhost/ums-webservice-common/academic/classroom/"+ encodeURIComponent(id));
      $("tr#" + lrid + " div.ui-inline-edit, " + "tr#" + lrid + " div.ui-inline-del").hide();
      $("tr#" + lrid + " div.ui-inline-save, " + "tr#" + lrid + " div.ui-inline-cancel").show();
    }


    });


  var addOptions = {
    keys: true,
    mtype: "POST",
    url: "AddUser",
    successfunc: function () {
      var $self = $(this);
      setTimeout(function () {
        $self.trigger("reloadGrid");
      }, 50);
    }
  };
  $("#jqGrid").jqGrid("inlineNav", "#jqGridPager", {
    addParams: {
      position: "last",
      addRowParams: addOptions
    }
  });

}

1 个答案:

答案 0 :(得分:1)

您使用的是哪个版本的jqGrid以及jqGrid的分支(free jqGridGuriddo jqGrid JS或版本中的旧jqGrid< = 4.7)?我开发了免费的jqGrid fork并实现了一些新功能,这些功能可以简化您的需求,并且还可以简化您的代码。

我建议您查看the answer。它展示了如何在免费的jqGrid中使用urlmtype 作为函数来为RESTful服务的使用创建简单明了的读取代码。

或者,您可以保留当前代码和当前使用的jqGrid版本,只是从type中删除ajaxRowOptions属性。除此之外,您只能将mtype参数与"PUT"值一起用于编辑选项,并将mtype: "POST"用于添加选项。