给表单加ID值,如图:
写ajax方法,如图:
servlet返回是否添加成功,如图:
jsp页面
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">新增角色信息</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" id="addRole">
<div class="form-group">
<label for="role_name" class="col-sm-2 control-label">角色名称</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="role_name" id="role_name" placeholder="请输入姓名">
</div>
</div>
<div class="form-group">
<label for="role_description" class="col-sm-2 control-label">角色描述</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="role_description" id="role_description" placeholder="请设置角色">
</div>
</div>
</form>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" id="BTN" class="btn btn-default">立即提交</button>
</div>
</div>
</div>
</div>
ajax方法
<script type="text/javascript">
$(function() {
$("#BTN").on("click", function() {
$.ajax({
type: "post",
url: "${pageContext.request.contextPath}/role?method=add",
data: $("#addRole").serialize(), // 序列化form表单里面的数据传到后台
//dataType: "json", // 指定后台传过来的数据是json格式
success: function(data){
if (data == "true") {
layer.msg('添加成功!', {
icon: 16
,shade: 0.01
});
} else {
layer.tips('添加失败!', '#BTN', {
tips: [2, '#3595CC'],
time: 2000
});
}
},
error: function(err){
alert("数据异常!");
}
})
})
})
</script>
servlet层
public void doadd(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Role role = new Role();
RequestUtil.copyProperty(request, role);
int i = roleDao.add(role);
boolean flag = false;//默认添加不成功
if (i > 0) {
flag = true;
} else {
flag = false;
}
PrintWriter out = response.getWriter();
out.print(flag); // 返回添加信息
out.flush();
out.close();
}