1. 程式人生 > >案例:Ajax非同步校驗使用者名稱是否存在

案例:Ajax非同步校驗使用者名稱是否存在


1.頁面程式碼:

<script type="text/javascript">
	$(function(){
		//為輸入框繫結事件
		$("#username").blur(function(){
			//1.失去焦點獲得輸入框的內容
			var usernameInput = $(this).val();
			//2.去伺服器校驗該使用者名稱是否存在--ajax
			$.post(
				"${pageContext.request.contextPath}/CheckUsernameServlet",
				{"username":usernameInput},
				function(data){
					//接收到CheckUsernameServlet返回的值
					var isExist = data.isExist;
					//3.根據返回的isExist動態顯示
					var uesrnameInfo = "";
					if(isExist){//對返回的值進行判斷
						usernameInfo = "該使用者名稱已經存在";
						$("#usernameInfo").css("color","red");//設定提示文字的顯示顏色
					}else{
						usernameInfo = "該使用者名稱可以使用";
						$("#usernameInfo").css("color","green");
					}
					//將提示資訊寫到使用者名稱框後面
					$("#usernameInfo").html(usernameInfo);
				},
				"json"
			);
		});
	});
</script>

2.web層:
public class CheckUsernameServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//獲取要校驗的使用者名稱
		String username = request.getParameter("username");
		//傳遞資料到service層
		UserService service = new UserService();
		boolean isExist = false;
		try {
			isExist = service.checkUsername(username);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		response.getWriter().write("{\"isExist\":"+isExist+"}");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

3.service層:
public class UserService {

	public boolean checkUsername(String username) throws SQLException {
		UserDao dao = new UserDao();
		Long isExist = dao.checkUsername(username);
		return isExist>0?true:false;
	}

}

4.dao層
public class UserDao {

	public Long checkUsername(String username) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource()); 
		String sql = "select count(*) from user where username=?";
		Long query = (Long) runner.query(sql, new ScalarHandler(), username);
		return query;
	}

}

效果: