ajax验证用户名是否已存在
ajax验证用户名是否已存在 ,一般选用的是同步请求,因为验证用户是否存在的同时,
一般还要验证用户名是否为空等表单验证。
jsp页面以及ajax验证如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){
$("#uname").blur(function(){
var uname = $(this).val();
if(uname==""){
$("#remind").html("用户名不能为空");
}else{
// $.ajax方法实现
$.ajax({
url:"IsUserServlet",
type:"get",
data:"uname="+uname,
dataType:"text",
async:false,
success:function(result){
$("#remind").html(result);
}
});
// $.get()方法实现,$.post方法也是一样的,post方法不能在地址后面直接传值
//$.get("IsUserServlet","uname=" + uname, function(result){
// $("#remind").html(result);
//},"text");
// load()方式实现
//$("#remind").load("IsUserServlet","uname=" + uname);
}
});
});
</script>
</head>
<body>
用户名:<input type="text" name="uanme" id="uname" /><span id="remind"></span>
</body>
</html>
控制层的servlet代码如下:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
User user = new User();
// 接收前端输入的用户名
String uname = request.getParameter("uname");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
UserService userService = new UserServiceImpl();
if(userService.login(uname)){
response.getWriter().write("用户名已存在");
}else{
response.getWriter().write("用户名不存在");
}
}
ajax验证用户名结果示例:
感谢您的阅读,欢迎参观我的个人网站:小嗨词典【 https://www.happydict.cn】