困扰了我一天的问题,写个博客记录下来。
参考博客:
展示一下完成后的界面:
1、创建提交按钮
<a style="margin-right:20%;margin-top:0.2%;width:10%;float:right;" class="button bg-main icon-check-square-o" onclick="submit1()">提 交</a>
这里的οnclick="submit1()"就是我们向后台提交数据的点击响应
2、创建按钮点击相应函数
<script>
//审核-一键审核
function submit1(){
var selectedRows = $("#bedRoomSelect").datagrid('getSelections');//得到选中的行
var collegeId = $("#college").val();
var grade = $("#grade").val();
var apartmentId = $("#apartment").val();
var floor = $("#floor").val();
if (collegeId=="" || grade == ""){
$.messager.alert("系统提示","请先选择分配的学院和年级。");
return;
}
if (selectedRows.length == 0) {
$.messager.alert("系统提示","请先选择要分配的宿舍。");
return;
}
var strIds = []; //1.批量审核 -就是一个数组存入多条选中的数据。
for ( var i = 0; i < selectedRows.length; i++) {
strIds.push(selectedRows[i].bedroomId);
}
var bedroomIds = strIds.join(","); //2.然后将数组转为字符串,逗号分隔
alert("已选中的宿舍ID为:"+bedroomIds);
$.messager.confirm("系统提示","本次分配共 <font color=red>"+selectedRows.length + "</font> 间宿舍。",
function(r) {if (r) {
$.post("${ctx}/statis/disbycollege.action",{
bedroomIds : bedroomIds,
collegeId : collegeId,
grade : grade,
apartmentId:apartmentId,
floor:floor
},
function(result) {if (result.success) {
$.messager.alert("系统提示","一键审核成功!");
$("#bedRoomSelect").datagrid("reload"); //重新加载
} else {
$.messager.alert("系统提示","一键审核失败,请检查数据!");
$("#bedRoomSelect").datagrid("reload"); //重新加载
}
}, "json");
}
});
}
</script>
首先我们需要获取我们想要提交的数据
var selectedRows = $("#bedRoomSelect").datagrid('getSelections');//得到选中的行
这里,是为了获取我们datagrid中选中的数据datagrid('getSelections'),然后将选中的宿舍ID添加到数组中,一起打包送给服务器,最后使用post方法,与后台服务器交互,前面的action就是在controller文件中定义的RequestMapping,后面{}中包含的就是你需要提交的数据,前面是参数名,必须与controller文件中的形参名对应,后面是需要提交的数据,这样就完成了前台数据请求的功能了。
$.post("${ctx}/statis/disbycollege.action",{
bedroomIds : bedroomIds,
collegeId : collegeId,
grade : grade,
apartmentId:apartmentId,
floor:floor
}
@RequestMapping("/statis/disbycollege.action")
3、后台接收数据
在这里我们可以使用@RequestParam来获取前端传过来的数据,需要注意的是value="param_name"中的param_name一定要与前端设置参数名一致。
@RequestMapping("/statis/disbycollege.action")
public String distributebycollege(@RequestParam(value="bedroomIds") String bedroomIds,
@RequestParam(value="collegeId") String collegeId,
@RequestParam(value="grade") String grade,
@RequestParam(value="apartmentId") String apartmentId,
@RequestParam(value="floor") String floor,
HttpServletResponse response) throws Exception {
到这里,基本上就已经实现了提交datagrid中选中的多行数据了,然后你就可以对这些数据做你想要的运算了。在下面我们提供了整个项目的部分代码,供大家参考。
项目部分代码
jsp文件
<%--
Created by IntelliJ IDEA.
User: 10086
Date: 2019/11/13
Time: 19:58
To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../basic/base.jsp"%>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="renderer" content="webkit">
<title></title>
<meta charset="UTF-8">
<title>Basic Layout - jQuery EasyUI Demo</title>
<link rel="stylesheet" type="text/css" href="../../themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="../../themes/icon.css">
<link rel="stylesheet" type="text/css" href="../demo.css">
<script type="text/javascript" src="../../jquery.min.js"></script>
<script type="text/javascript" src="../../jquery.easyui.min.js"></script>
</head>
<body>
<div style="width:1920px;height:1080px;" class="panel admin-panel">
<div class="panel-head" id="add"><strong><span class="icon-pencil-square-o"></span>按个人快速分配宿舍</strong></div>
<div class="body-content">
<form method="post" class="form-x" action="${ctx}/statis/disbycollege.action">
<div style="margin:0%;"></div>
<div class="easyui-layout" style="width:1920px;height:960px;">
<div data-options="region:'north'" style="height:50px">
<div class="label" style="margin-left:2%;margin-top:0.8%;width:7%;float:left;">
<label>请选择公寓:</label>
</div>
<select id="apartment" class="input" name="apartmentId" onchange="tips2(this.value)"
style="margin-left:0px;margin-top:0.3%;width:10%; float:left; line-height:120%;">
<option value="">选择公寓</option>
<c:forEach var="s" items="${apartmentList}">
<option value="${s.apartmentId}">${s.apartmentName}</option>
</c:forEach>
</select>
<select id="floor" class="input" name="floor"
style="margin-left:1%;width:10%;float:left;margin-top:0.3%; line-height:120%;" onchange="afterSelectFloor('bedRoomSelect','apartment',this.value)">
<option value="">选择楼层</option>
</select>
<div class="label" style="margin-left:2%;margin-top:0.8%;width:7%;float:left;">
<label>分配到:</label>
</div>
<select id="college" class="input" name="collegeId"
style="margin-left:1%;width:10%;float:left;margin-top:0.2%; line-height:120%;" >
<option value="">选择学院</option>
<c:forEach var="s" items="${collegeList}">
<option value="${s.collegeId}">${s.collegeName}</option>
</c:forEach>
</select>
<select id="grade" class="input" name="grade"
style="margin-left:1%;width:10%;float:left;margin-top:0.2%; line-height:120%;">
<option value="">选择年级</option>
<option value="d1">大一</option>
<option value="d2">大二</option>
<option value="d3">大三</option>
<option value="d4">大四</option>
<option value="y1">研一</option>
<option value="y2">研二</option>
<option value="y3">研三</option>
</select>
<a style="margin-right:20%;margin-top:0.2%;width:10%;float:right;" class="button bg-main icon-check-square-o" onclick="submit1()">提 交</a>
<script>
//审核-一键审核
function submit1(){
var selectedRows = $("#bedRoomSelect").datagrid('getSelections');//得到选中的行
var collegeId = $("#college").val();
var grade = $("#grade").val();
var apartmentId = $("#apartment").val();
var floor = $("#floor").val();
if (collegeId=="" || grade == ""){
$.messager.alert("系统提示","请先选择分配的学院和年级。");
return;
}
if (selectedRows.length == 0) {
$.messager.alert("系统提示","请先选择要分配的宿舍。");
return;
}
var strIds = []; //1.批量审核 -就是一个数组存入多条选中的数据。
for ( var i = 0; i < selectedRows.length; i++) {
strIds.push(selectedRows[i].bedroomId);
}
var bedroomIds = strIds.join(","); //2.然后将数组转为字符串,逗号分隔
alert("已选中的宿舍ID为:"+bedroomIds);
$.messager.confirm("系统提示","本次分配共 <font color=red>"+selectedRows.length + "</font> 间宿舍。",
function(r) {if (r) {
$.post("${ctx}/statis/disbycollege.action",{
bedroomIds : bedroomIds,
collegeId : collegeId,
grade : grade,
apartmentId:apartmentId,
floor:floor
},
function(result) {if (result.success) {
$.messager.alert("系统提示","一键审核成功!");
$("#bedRoomSelect").datagrid("reload"); //重新加载
} else {
$.messager.alert("系统提示","一键审核失败,请检查数据!");
$("#bedRoomSelect").datagrid("reload"); //重新加载
}
}, "json");
}
});
}
function submit() {
var collegeId = $("#college").val();
var rows = $('#bedRoomSelect').datagrid('getSelections');
alert(rows);
$.messager.confirm('确认', '确定要提交所有的数据?', function(r) {
if (r) {
$.ajax({
type : "post",
url : '${ctx}/statis/disbycollege.action',
data : {
json : JSON.stringify(rows),
collegeId : collegeId
},
dataType : "JSON",
success : function(data, textStatus) {
if (data.resultCode == 1) {
showRightBottomMsg("系统提示", "提交成功!", 'slide',
5000);
clearDatagridAndTree();
} else {
if (data.errorType == "user") {
showAlertMsg("提示", data.msg, "warning");
} else {
showRightBottomMsg("系统提示", data.msg,
'slide', 5000);
}
}
},
error : function(XMLHttpRequest, textStatus,
errorThrown) {
alert(textStatus + errorThrown);
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});
}
});}
</script>
</div>
<div class="easyui-panel" style="position:relative;width:500px;height:300px;overflow:auto;">
<div id="w2" class="easyui-window" title="Modal Window" data-options="modal:true,closed:true,iconCls:'icon-save'" style="width:500px;height:200px;padding:10px;">
The window content.
</div>
</div>
<div data-options="region:'south',split:true" style="height:50px">
<li>说明:</li>
</div>
///查看宿舍信息
<div id="dl" data-options="region:'east',split:true" title="查看宿舍信息" style="width:150px;">
<li value="WY" style="margin-top: 30%;">在这里查看宿舍信息。</li>
</div>
///已选择宿舍
<div id="choseBedroom",data-options="region:'west',split:true" title="已选择宿舍" style="width:200px;">
<li value="WY" style="margin-top: 30%;">在这里查看已选中的宿舍。</li>
</div>
<div data-options="region:'center',title:'欢迎进入武科大宿舍管理系统!',iconCls:'icon-ok'">
<table id="bedRoomSelect" class="easyui-datagrid"
data-options="method:'get',border:false,singleSelect:false,fit:true,fitColumns:true"
>
<thead>
<tr>
<th data-options="field:'ck',checkbox:true"></th>
<th data-options="field:'bedroomId',align:'center'" width="10%">宿舍编号</th>
<th data-options="field:'bedroomName',align:'center'" width="10%">宿舍名称</th>
<th data-options="field:'apartmentId',align:'center'" width="10%">所属公寓</th>
<th data-options="field:'checkedNum',align:'center'" width="5%">已入住人数</th>
<th data-options="field:'unCheckedNum',align:'center'" width="5%">剩余床位</th>
<th data-options="field:'status',align:'center'" width="5%" >选择状态</th>
<th data-options="field:'classId',align:'center'" width="10%" >所属班级</th>
<th data-options="field:'collegeId',align:'center'" width="10%" >所属学院</th>
<th data-options="field:'grade',align:'center'" width="10%" >所属年级</th>
<th data-options="field:'_operate',align:'center',formatter:formatOper" width="10%" >操作</th>
</tr>
</thead>
</table>
</div>
</div>
<c:if test="${sessionScope.type=='student'}">
<!--------------------------------------------------------------------------------------------------->
</c:if>
</form>
</div>
<script type="text/javascript" src="datagrid-filter.js">
$(function(){
var dg = $('#bedRoomSelect').datagrid();
dg.datagrid('enableFilter');
})
</script>
<script type="text/javascript">
function formatOper(val, row, index) {
return '<a href="javascript:void(0)" onclick="showUser(' + index
+ ')">查看</a> <a href="javascript:void(0)" onclick="editTeacher(' + index
+ ')">修改</a> <a href="javascript:void(0)" onclick="dele()">删除</a> ';
}
function dele() {
var rows = $('#dg').datagrid('getSelections');
alert(rows)
/*if (rows.length > 0) {
$.messager.confirm('批量删除', '选中的信息是否全部删除?', function(r) {
if (r) {
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
$.ajax({
type : 'POST',
url : 'kxdel.action',
async : false,
data : {
id : row.kxid
},dataType : 'json',
});
}
location.reload();
}
});
}*/
}
function ejld2(sex){
// $("#sex2").val($("#sex2 option:selected").text());
$.ajax({
type: "GET",
url: "${ctx}/apm/getdata.action",
data: {"sex":sex},
dataType: "json",
success:function(data){
$("#apartment").empty();
$("#apartment").append('<option>选择公寓</option>');
$.each(data,function(index,item){
$("#apartment").append('<option value="'+item["apartmentId"]+'">'+item["apartmentName"]+'</option>');
});
},
error:function(){
alert("eeror json");
}
});
}
function tips1(collegeId){
$.ajax({
type: "POST",
url: "${ctx}/stu/getdata2.action",
data: {"collegeId":collegeId},
dataType: "json",
success:function(data){
$("#tips1").empty();
$("#tips1").html(data["tips1"]);
},
error:function(){
alert("eeror json");
}
});
}
function tips2(apmId){
initFloor("floor",apmId);
}
function tips3(apmId){
initCombogrid("bedRoomSelect2",apmId);
initFloor("floor2",apmId);
}
function afterSelectFloor(selectedId,apmId,floor) {
var apmValue = $("#"+apmId).val();
initCombogrid(selectedId,apmValue,floor);
}
function initFloor(selectId,apmId) {
$.ajax({
type: "GET",
url: "${ctx}/apm/gettotalfloor.action",
data: {apartmentId: apmId },
dataType: "json",
success:function(data){
var floor=data['floor'];
if(floor<1 || floor==null) floor=1;
$("#floor").empty();
$("#bedRoomSelect").datagrid('loadData', { total: 0, rows: [], footer: [] }); // 当转换公寓后,清空table
$("#floor").append('<option value="">选择楼层</option>'); // 为floor增加选项
for(var i=1;i<=floor;i++){
$("#"+selectId).append('<option value="'+i+'">'+i+'楼'+'</option>');
}
},
error:function(json){
alert("请选择公寓!");
}
});
}
</script>
<script>
function initCombogrid(selectedId,apartmentId,floor) {
if (!apartmentId) {
apartmentId = 111;
}
$("#"+selectedId).datagrid({
multiple: true,
idField: 'bedroomId',
textField: 'bedroomName',
url: '${ctx}/br/getBedInfo1.action?apartmendId='+apartmentId+'&floor='+floor,
method: 'get',
fitColumns: true,
labelPosition: 'top',
pagination: true,
clientPaging: false,
remoteFilter: true,
rownumbers: true
/*onClickRow:function(index, row){
var _bedroomName = row.bedroomName;
var _bedroomId = row.bedroomId;
if (row){
document.getElementById("test").value="已选择宿舍:" + _bedroomName;
showRoommate(_bedroomId);
}
}*/
})
}
</script>
<script>
function showRoomamte1(bedroomId){
$('#dl').datalist({
url: '${ctx}/statis/findbybedroomid.action?bedroomId='+bedroomId,
checkbox: true,
lines: true
});
}
function showRoommate(bedroomId){
$.ajax({
type: "GET",
url: "${ctx}/statis/findbybedroomid.action",
data: {bedroomId:bedroomId},
dataType: "json",
success:function(data){
$('#dl').empty();
$.each(data,function(index,item){
$('#dl').append('<li style="margin-top: 4%;text-align: center" value="'+item["studentId"]+'">'+item["studentName"]+'</li>');
});
},
error:function(json){
alert(json);
}
});
}
</script>
<script>
function getSelected(){
var row = $('#showroommate').datagrid('getSelected');
if (row){
$.messager.alert('Info', row.bedroomName+":"+row.apartmentName+":"+row.checkedNum);
}
}
function getSelections(){
var ss = [];
var rows = $('#bedRoomSelect').datagrid('getSelections');
for(var i=0; i<rows.length; i++){
var row = rows[i];
ss.push('<span>'+row.bedroomName+":"+row.apartmentName+":"+row.checkedNum+'</span>');
}
$.messager.alert('Info', ss.join('<br/>'));
}
function checkBox(firstID, finalID){
var ss = [];
var rows = $('#bedRoomSelect').datagrid('getSelections');
for(var i=0; i<rows.length; i++){
var row = rows[i];
ss.push('<span>'+row.bedroomName+":"+row.apartmentName+":"+row.checkedNum+'</span>');
}
$.messager.alert('Info', ss.join('<br/>'));
}
</script>
</div>
</body></html>
cotroller文件
@RequestMapping("/statis/disbycollege.action")
public String distributebycollege(@RequestParam(value="bedroomIds") String bedroomIds,
@RequestParam(value="collegeId") String collegeId,
@RequestParam(value="grade") String grade,
@RequestParam(value="apartmentId") String apartmentId,
@RequestParam(value="floor") String floor,
HttpServletResponse response) throws Exception {
System.out.println("进入一键分配,分配的宿舍id为:"+bedroomIds);
String[] bedroomIdlist = bedroomIds.split(","); //字符串以逗号切割存入数组
//通过状态
for (int i = 0; i < bedroomIdlist.length; i++) { //循环执行一键审核操作
try {
String bedroomId = bedroomIdlist[i];
Bedroom bedroom = bedroomService.get(bedroomId);
bedroom.setCollegeId(collegeId);
bedroom.setGrade(grade);
bedroomService.update(bedroom);
System.out.println("分配成功。");
} catch (Exception e) {
System.out.println("分配失败。");
}
}
return null;
}