<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" onclick="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";}