需要使用开启头部标题栏的数据表格
新增数据
1.设置添加按钮
<script type="text/html" id="toolbarDemo">
<div class="layui-btn-container">
<button type="button" class="layui-btn layui-btn-sm" id="add" lay-event="add">添加</button>
</div>
</script>
设置点击事件
//头工具栏事件
table.on('toolbar(test)', function(obj){
var checkStatus = table.checkStatus(obj.config.id);
switch(obj.event){
case 'add':
add();
break;
};
});
2.设置弹窗
首先先写一个方法,该方法的目的是将弹框弹出了
function add(){
layer_index= layer.open({
type: 1, //可传入的值有:0(信息框,默认)1(页面层)2(iframe层)3(加载层)4(tips层)
title: "添加", //数组第二项可以写任意css样式;如果你不想显示标题栏,你可以title: false
area: ['500px', '400px'], //所打开页面大小
content:$("#addForm"), //内容
//关闭操作
cancel: function(){
layer.close(layer_index);
$("#addForm")[0].reset();
$('#demoe1').attr('src', "");
}
});
//刷新页面
table.reload('test', {
url: 'http://localhost:8080/xinshijiServlet/DemoServlet'
});
}
设置from表单
<!-- 添加的from表单 -->
<form class="layui-form" action="" id="addForm" style="display:none" lay-filter="add" enctype="multipart/form-data">
<div class="layui-form-item">
<label class="layui-form-label">用户名</label>
<div class="layui-input-block">
<input type="text" id="username" name="username" lay-verify="title" autocomplete="off" placeholder="用户名" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">手机号</label>
<div class="layui-input-block">
<input type="text" id="phone" name="phone" lay-verify="title" autocomplete="off" placeholder="手机号" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">性别</label>
<div class="layui-input-block">
<input type="text" id="sex" name="sex" lay-verify="title" autocomplete="off" placeholder="性别" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">年龄</label>
<div class="layui-input-block">
<input type="text" id="age" name="age" lay-verify="title" autocomplete="off" placeholder="年龄" class="layui-input">
</div>
</div>
<div class="layui-form-item" id="sub">
<button style="" class="layui-btn" type="button" lay-submit lay-filter="demo2" id="addsub">提交</button>
</div>
</div>
</form>
form表单提交
//引入from表单
layui.use(['form', 'laydate'], function(){
form = layui.form;
form.render();
//表单取值
form.on('submit(demo2)', function(data){
console.log(JSON.stringify(data.field));
$.ajax({
url:'/xinshijiServlet/AddContentServlet',
method:'get',
data:data.field,
dataType:'JSON',
success:function(res){
if(res.status='0'){
console.log(res);
layer.msg("添加成功");
$("#addForm")[0].reset();
form.render();
page();
}else{
layer.msg("添加失败");
$("#addForm")[0].reset();
form.render();
}
},
error:function (data) {
layer.msg("网络错误");
$("#addForm")[0].reset();
form.render();
}
}) ;
layer.close(layer_index);
});
});
返回类型设置为json类型,否则就会出网络异常
String data = "{\"data\":\"返回成功\"}";
return data;