jquery和ajax异步验证 1,js页面
<!-- 登陆验证 -->
<script type="text/javascript" src="<%=request.getContextPath() %>/static/js/jquery.js"></script>
<script type="text/javascript">
function test(){
var name=$("#again").val();
$.ajax({
type:"get",
url:"<%=request.getContextPath()%>/stu/exist",
/*前面个name为传到Java代码里面的属性,使用与实体类一样的,可以采用SpringMVC约定大于配置的原则直接使用Stu的实体类即可*/
data:{"name":name},
dataType:"json",
success:function(urse){
if(urse.exist=="no"){
$("#ax").css("color","red").html("用户名不存在");
/* 若用户名不存在,不让用户点击提交按钮 */
document.getElementById("dis").disabled="disabled";
}
}
})
}
</script>
<form action="">
用户名:<input type="text" name="name" id="again" onblur="test()"><span id="ax"></span><br/>
密码:<input type="password" name="pwd" ><br/>
<input type="submit" name="提交" id="dis"><br/>
</form>
## java页面`//判断用户名是否可用
@RequestMapping("/exist")
@ResponseBody//必须有这个
public Object selName(@ModelAttribute("stu")Stu stu) {
st=(StuService) BaseServlet.get("stu");
List<Stu> list=st.selAll(stu);
Map<String, String> map=new HashMap<String,String>();
if(list.size()>0) {
map.put("exist", "yes");
}else {
map.put("exist", "no");
}
return JSON.toJSONString(map);
} `
```## springmvc.xml配置`
<mvc:resources location="/static/" mapping="/static/**"></mvc:resources>
## 所需资源![路径为/static/js/jquery.js](https://img-blog.csdnimg.cn/20181105160452400.png)
还需要一个 fastjson-1.2.13.jar的包