咔片PPT · AI自动生成演示文稿,模板丰富、排版精美 讯飞智文 · 一键生成PPT和Word,高效应对学习与办公

需求目的:

双击web单元格编辑后,保存数据到mongodb数据库。就像Excel那样更新数据。

1. 首先Layui 标识列可单击修改

添加 edit:text标识,标识列可修改

{field: 'Id', title: '编号', width: 80, sort: true, fixed: 'left'} ,{field: 'username', title: '用户名' , edit: 'text'} ,{field: 'gender', title: '性别', width: 80 , edit: 'text'} ,{field: 'password', title: '密码', width: 80 , edit: 'text'} ,{field: 'address', title: '地址', width: 80 , edit: 'text'} ,{field: 'email', title: '邮箱', width: 80 , edit: 'text'} ,{field: 'phone', title: '电话', width: 80 , edit: 'text'}

此时点击数据表,可看到数据表进入编辑模式


2. 获取编辑表格事件,添加列修改后监听:

//监听单元格编辑 table.on('edit(test_table)', function (obj) { var value = obj.value //得到修改后的值 , data = obj.data //得到所在行所有键值 , field = obj.field; //得到字段 layer.msg('[ID: ' + data.Id + '] ' + field + ' 字段更改为:' + value); console.log(data.Id); var jsonResult = dataServer.updateUserInfo(obj.data); if(jsonResult==1){ layer.alert("更新成功", {icon: 6},function () { x_admin_father_reload(); }); }else{ layer.msg("更新成功!"); } });

3. 后台添加对应的编辑修改接口:

/** 修改用户列表 */ func (m UserC) Update(g *gin.Context) { rsp := new(Rsp) var info models.User err := g.BindJSON(&info) if err != nil { rsp.Msg = "json faild" rsp.Code = 201 g.JSON(http.StatusOK, rsp) return } if info.Id.String() == "" { rsp.Msg = "id is empty!" rsp.Code = 201 g.JSON(http.StatusOK, rsp) return } filter := bson.D{{"_id", info.Id}} //selector := bson.M{"_id": updateId} //updateInfo,_ :=bson.Marshal(&info) result := m.Mgo.Collection(db.User).FindOneAndReplace(context.Background(), filter, info) if result != nil { if result.Err() != nil { fmt.Println(result.Err()) } rsp.Msg = "success" rsp.Code = 200 rsp.Data = 1 g.JSON(http.StatusOK, rsp) return } rsp.Msg = "err" rsp.Code = 201 rsp.Data = 0 g.JSON(http.StatusOK, rsp) return }

4. 查看完成效果:

单击表格并编辑成功!

获取源代码请转发后回复:1