AJAX异步判断用户名是否已被注册
在用户注册时,常常遇到用户名冲突问题,即用户名已经被注册了,当用户填写完大段表单然后点击注册发现自己输入的用户名无效,这样会降低用户注册的积极性。
AJAX能很好的解决这一问题,在用户输入用户名时,会异步发送请求到服务器,即能做出判断,该用户名是否已经存在,然后提示用户。
下面举一个简单的例子,分为表单页面和服务器端处理页面。
表单页面:helloworld.html
<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<body>
<form name="myForm">
<input type="text" name="world" onkeyup="showHello(this.value)">
<span id="txtHint"></span>
</form>
<script type="text/javascript">
var xmlHttp;
function showHello(value){
//针对不同浏览器,不同的方式生成xmlHttp对象
try{
xmlHttp=new XMLHttpRequest();
}catch(e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHttp");
}catch(e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHttp");
}catch(e){
alert("你的浏览器不支持AJAX") ;
return false;
}
}
}
var url="helloworld.jsp?username="+value;
xmlHttp.onreadystatechange=deal;//该属性为一个函数
xmlHttp.open("GET",url,false);//初始化xmlHttp
xmlHttp.send(null);//发送
}
function deal(){
if(xmlHttp.readyState==4){//当状态值为4时,接收到服务器传输的信息
var txtHint=xmlHttp.responseText;
document.getElementById("txtHint").innerHTML=txtHint;
}
}
</script>
</body>
</html>服务器端处理页面:helloworld.jsp<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
</head>
<body>
<%!
ResultSet rs = null;
Connection con = null;
PreparedStatement pst = null;
%>
<%
//从URL中获取参数
String username = request.getParameter("username");
//操作数据库
try{
Class.forName("com.mysql.jdbc.Driver");//加载mysql数据库驱动,驱动包要先导入好
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "root", "admin");
pst = con.prepareStatement("SELECT * FROM user_info WHERE username=?");
pst.setString(1, username);//注入方式
System.out.println(username);
rs = pst.executeQuery();
}catch(Exception e){
e.printStackTrace();
}
//输出到客户端
if(rs.next()){
out.print("该用户名已经存在!");
}else{
out.print("该用户名可用!");
}
%>
</body>
</html>注意:一般jsp页面中不要出现太多java代码,如对数据库的操作代码都可以封装到类中去,方便维护,但是这里为了方便展示。
本文介绍如何利用AJAX技术实现前端与后台JavaWeb应用的异步交互,实时验证用户名是否已被注册,避免传统页面刷新带来的用户体验问题。
644

被折叠的 条评论
为什么被折叠?



