代码示例:
jsp页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
body{
width: 400px;
text-align: right;
}
</style>
<script type="text/javascript" src="${pageContext.request.contextPath}/jquery-1.7.2.js"></script>
<script type="text/javascript">
/* ajax异步请求 */
$(function(){
$("[name=cardId]").blur(function(){
$.post("${pageContext.request.contextPath}/UserServlet",{"cardId":$(this).val(),"method":"backJson"},function(data){
if(data){
//字符串转成json
//var json= JSON.parse(data);
console.log(data.cardId);
$("#span").text("身份证号["+data.cardId+"]已存在");
}else{
$("#span").text("身份证号可使用");
}
},"json");
})
})
</script>
</head>
<body>
<h1>账号注册</h1>
<form action="${pageContext.request.contextPath}/UserServlet?method=regist" method="post">
身份证号:<input type="text" name="cardId" value="${param.cardId}"/><br/>
<span id="span"></span><br/>
用户名:<input type="text" name="name" value="${param.name}"/><br/>
密码:<input type="text" name="password" value="${param.password}"/><br/>
确认密码:<input type="text" name="qrpwd" value="${param.qrpwd}"/><br/>
<input type="submit" value="注册">
<input type="button" value="返回" onclick="window.location.href='http://localhost:8080/family_work/login.jsp'"/>
<p>${msg}</p>
</form>
</body>
</html>
servlet页面:
protected void backJson(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
User bean = WEBUtils.getRequestBean(request, User.class);
User user = us.login(bean);
if(user!=null){
//对象序列化为json字符串,方法省略
String jsonStr = GsonUtils.objectToJsonStr(user);
response.getWriter().print(jsonStr);
}
}