实现输入框输入结束后自动提交到后台进行异步验证数据库中是否已经存在。
jsp页面关键代码:
<div id="document" class= "page-content" >
<form class= "form-horizontal" role ="form" novalidate="novalidate" >
<div class= "form-group">
<label class= "col-sm-3 control-label no-padding-right" for= "shipversion">
型号 </label>
<div class= "col-lg-6">
<input type= "text" id ="shipversion"
class="col-lg-6 col-sm-5" />
<span id= "checkResult"></span >
</div>
</div>
……
jquery关键代码:
< script src= './js/jquery-2.0.3.min.js' ></ script> //一定需要添加jquery
< script type= "text/javascript">
$(document).ready(function() {
$("#checkResult").html("" );
$("#shipversion").blur(function () {
$.ajax({
url:' <%=path %>/versionExistAction ',type : 'POST',data : {shipversion:$( "#shipversion").val()},success : function(data) {
if(data.versionIsUsed==true){
$( "#checkResult").html("<font color='red'>该型号已经存在,请重新输入! </font>" );
} else{
$( "#checkResult").html("<font color='green'>该型号尚不存在,可以添加! </font>" );
}
},error : function() {
alert( '发生错误');
}
});
});
});
action中关键代码:
public void existVersion(){
if(shipversion !="" ){
Warship ship=warshipService.queryWarshipByShipversion(shipversion );
if(ship==null ){
versionIsUsed=false ;
} else{
versionIsUsed=true ;
}
}
}
struts中配置文件:
<package name= "addWeapon" extends ="json-default" namespace="/" >
<action name= "versionExistAction" class ="warshipAction" method="existVersion" >
<result type= "json" ></ result>
</action>
</package>