需求:根据id批量删除数据
分析前端获取多选或者单选的id的数组
前端代码:用的jquery-easyui
$("#remove").bind("click", function() {
//debugger
//获取表单easyui的datagrid
var customerList = $("#customerList");
/*[item,item,item,item]*/
//获取easyui表格的选中属性
var sels = customerList.datagrid("getSelections");
//定义一个空数组
var ids = [];
console.log(typeof (sels[0].cust_id));
for ( var i in sels) {
//遍历数组中的对象获取数组对象的id放到数组中
ids.push(sels[i].cust_id);
}
console.log(ids); //这是[1,2,3]
ids = ids.join(",");//变成了1,2,3如果不进行这一步后台接收会是这样[[1,2,3]]
console.log(ids);//将数组拼接成字符串 1,2,3,4,5
$.post("customer/remove", {
"ids" : ids
}, function(result) {
if (result.state == 1) {
alert("删除成功");
$("#customerList").datagrid("reload");
} else {
alert("删除失败");
}
})
})
后台controller:
@RequestMapping("customer/remove")
@ResponseBody
public ResultJson removeCustomer(Integer[] ids) {
try {
customerMapper.deleteCustomerByIds(ids);
// int a=1/0;
} catch (Exception e) {
e.printStackTrace();
return new ResultJson(e);
}
return new ResultJson();
}
举个例子:
前端代码:
$("#btn1").click(function(){
var array=[1,2,3];
//这个join方法的用处看下面
array=array.join(',');
console.log(array);
$.post('${pageContext.request.contextPath}/toweb/http3',{"ids":array},function(data){
console.log(data.name);
})
})
join方法:
join 方法
返回字符串值,其中包含了连接到一起的数组的所有元素,元素由指定的分隔符分隔开来。
arrayObj.join(separator)
参数
arrayObj
必选项。Array 对象。
separator
必选项。是一个 String 对象,作为最终的 String 对象中对数组元素之间的分隔符。如果省略了这个参数,那么数组元素之间就用一个逗号来分隔。
说明
如果数组中有元素没有定义或者为 null,将其作为空字符串处理。
示例
下面这个例子说明了 join 方法的用法。
function JoinDemo(){
var a, b;
a = new Array(0,1,2,3,4);
b = a.join("-");
return(b);
}
后台代码:
/* 后台接收
* 1.String[] ids 效果是[1,2,3]
* */ 2.Integer[] ids 效果一样 看你要什么
@RequestMapping("http3")
@ResponseBody
public Data tohttp3( Integer[] ids) {
Data data=new Data();
data.setId("1");
data.setName("zs");
return data;
}
总结:前端是无法直接将数组传过来的,必须将数组转化为字符串再传到后端
方便自己查看:
function doGetCheckedIds(){
//1.定义存储选中id的数组对象
var array=[];//new Array();
//2.获取tbody中所有checked对象
$("#tbodyId input[type='checkbox']")
//迭代所有checkbox对象
.each(function(){
//获取checkbox对象中checked属性的值
var checked=$(this).prop("checked");
//检测checkbox对象状态
if(checked){
//假如是选中状态,则将对象的value值存储到数组
array.push($(this).val());
}
});
//3.返回数组
return array;
}
//执行删除操作
function doDeleteObjects(){
debugger
//1.获取用户选中的记录id,并进行判定
var idArray=doGetCheckedIds();
if(idArray.length==0){
alert("请先选中");
return;
}
//2.给出提示,"您确认删除吗"
if(!confirm("确定删除吗"))return;
//3.执行删除业务
//3.1定义请求参数
var params={"ids":idArray.toString()};//1,2,3
//3.2定义请求url
var url="log/doDeleteObjects";
//3.3发送异步请求执行删除操作。
$.post(url,params,function(result){
if(result.state==1){
alert(result.message);
doDeleteRefreshPage();//刷新页面
}else{
alert(result.message);
}
})
}