jQuery中ajax用form表单方式提交数据

给表单加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">&times;</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();
}
  • 5
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值