一、jquery引用
主要用到3个js:
jquery.js
jquery.form.js
jquery.validation.js
另外,为了校验结果提示本地化,还需要引入jquery.validate对应的mesage_zh.js。
这个几个文件的地址就不一一整理了,可以在官网上去下载,也可以在CathyCMS项目中拷贝。
二、html页面
权限管理的新增角色页面,不考虑资源树部分的话,这个页面的内容和交互比较简单,我们就以这个页面为例,看下怎么实现表单校验和异步提交。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
<
form
id="myForm" class="form-horizontal" th:object="${role}">
<
input
type="hidden" th:field="*{roleId}">
<
fieldset
>
<
div
class="control-group">
<
label
class="control-label" for="name">角色名称</
label
>
<
div
class="controls">
<
input
type="text" class="input-xlarge" th:field="*{name}">
</
div
>
</
div
>
<
div
class="control-group">
<
label
class="control-label" for="description">角色描述</
label
>
<
div
class="controls">
<
textarea
class="input-xlarge" th:field="*{description}" rows="3"></
textarea
>
</
div
>
</
div
>
<
div
class="control-group">
<
label
class="control-label" for="select01">Client</
label
>
<
div
class="controls">
<
select
id="select01">
<
option
>-- Select client --</
option
>
<
option
>Bad Robot</
option
>
<
option
>Evil Genius</
option
>
<
option
>Monsters Inc</
option
>
</
select
>
</
div
>
</
div
>
<
div
class="form-actions">
<
button
type="submit" class="btn btn-primary">保存</
button
>
<
button
class="btn">返回列表</
button
>
</
div
>
</
fieldset
>
</
form
>
|
三、表单校验部分脚本
这个页面要求角色名称必填,如果校验不合格在当前页面给出提示;如果校验合格就提交ajax请求。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
<script type=
"text/javascript"
>
$.validator.setDefaults({
submitHandler:
function
(form) {
$(form).ajaxSubmit({
url:
"[[@{/role/save}]]"
,
type:
"post"
,
dataType:
"json"
,
success:
function
(json){
if
(json!=
null
&&json.returncode==0){
window.location.href=
"[[@{/role/list}]]"
;
}
else
{
alert(
"保存失败"
);
}
}
});
}
});
$().ready(
function
() {
$(
"#myForm"
).validate({
rules: {
name:
"required"
},
messages: {
name:
"请输入角色名称"
}
});
});
</script>
|
四、后台action
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
@RequestMapping(
"/save"
)
@ResponseBody
public JsonResult save(CmsRole role){
JsonResult jsonResult=
new
JsonResult(){{
setReturncode(-1);
setMessage(
"保存失败"
);
}};
int result;
if
(role.getRoleId()==
null
||role.getRoleId()==0){
result=roleService.insert(role);
}
else
{
result=roleService.update(role);
}
if
(result>0){
jsonResult.setReturncode(0);
jsonResult.setMessage(
"保存成功"
);
}
return
jsonResult;
}
|
本文转自 陈敬(Cathy) 博客园博客,原文链接:http://www.cnblogs.com/janes/p/7553137.html,如需转载请自行联系原作者