开发过程中,可能会涉及到表单提交,如果直接提交,那整个页面会刷新,并且也无法获取对应的提示信息。所以表单提交通常用ajax来实现,如果整个表单的字段很多,一个个的拼接很麻烦,这里介绍一个工具
common.js代码
//form序列化为json
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
前端页面
导入js
<script src="${pageContext.request.contextPath}/js/comm/common.js"></script>
使用方法:
/**
* 提交修改数据
*/
function submitUpdate(){
var formdata = $("#roleForm").serializeObject();
var url = "update";
$.ajax({
type : "Post",
contentType : "application/json; charset=utf-8",
// 方法所在页面和方法名
dataType : "json",
data : JSON.stringify(formdata),
url : url,
success : function(data) {
if(data.code == 0){
return layer.msg(data.error);
}else{ //成功
layer.closeAll();
layer.msg(data.error, {icon: 1});
setTimeout(function(){
$("#form").submit();
},2000);
}
}
});
}
注意这里的#form是表单的值
后台代码:
/**
* 新增或者修改权限 根据id判断是新增还是修改
* @param authority
* @return
*/
@SuppressWarnings("all")
@RequestMapping(value = "update")
@ResponseBody
public BaseDataResult update(@RequestBody RoleVo role){
Principal principal = getLoginAdminInfo();
if(null == principal){
logger.info("--------------获取登录用户身份信息为空!");
return new BaseDataResult(Constans.FAILED, "获取登录用户身份信息为空");
}
BaseDataResult result;
OperationType type = null;
try {
if(role != null && role.getId() == null) { //新增
type = OperationType.ADD;
}
if(role != null && role.getId() != null) { //修改
type = OperationType.UPDATE;
}
result = roleServiceImpl.insertOrUpdate(role,principal,type);
} catch (Exception e) {
return new BaseDataResult(Constans.FAILED, type.getDesc()+"操作异常");
}
return result;
}
程序猿学社
认证博客专家
Java
Spring Boot
公众号程序猿学社,关注社长,跟着社长一起学习github文章系统整理https://github.com/ITfqyd/cxyxs