<pre class="html" name="code">form表单
<form:form id="inputForm" modelAttribute="user" action="/user/save" method="post" class="form-horizontal">
<form:hidden path="id"/>
<label style="height: 30px;margin-top: -20px;" type="hidden" id="msgs" name="msgs" class="error"> </label>
<div class="control-group">
<label class="control-label" >用户名</label>
<div class="controls">
<form:select path="name">
<form:options items="${name}" class="required"/>
</form:select>
</div>
</div>
<div class="control-group">
<label class="control-label" >密码</label>
<div class="controls">
<form:select path="pwd">
<form:options items="${pwd}" class="required"/>
</form:select>
</div>
</div>
<div class="form-actions">
<input id="btnSubmit" class="btn btn-primary" type="button" οnclick="save()" value="保 存"/>
</div>
</form:form>
前台js
<script type="text/javascript">
//查看用户名在数据库中是否唯一
function save(){
$.ajax({
url:"/user/checkSave",
type: "get", //数据发送方式
dataType: "json", //接受数据格式
cache:false,
async:false,
//获取form表单,往后台传
data:$('#inputForm').serialize(),
success:function(mssg){
//false为有,true为没有
if(mssg==true){
//如果返回true则提交from表单
document.getElementById("inputForm").submit();
}else{
//如果返回false,则在界面提示用户
document.getElementById("msgs").style.display = "block";
document.getElementById("msgs").innerHTML=mssg.msg;
return false;
}
}
});
}
</script>
<pre class="java" name="code">后台controller
@ResponseBody
@RequestMapping("checkSave")public String checkSave(User user, HttpServletResponse response, HttpServletRequest request) {//。。。获得用户名,在数据库中进行一系列判断,省略此代码//如果数据库中已有该登录名,则提示用户String msg="";if(!msg.equals("")){ String result = "{\"msg\":\"该"+msg+"已存在,请重新输入!\"}"; try { //用json格式在前台显示出来 PrintWriter out = null; response.setContentType("application/json"); out = response.getWriter(); out.write(result); response.reset();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} return result;}return "true";}