日期:2014-05-16  浏览次数:20645 次

Ajax案例(2)
function checkName(str){
	if(str==""||str==null){
		return;
	}
	var xmlhttp;
	if(window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
		if(xmlhttp.readyState==4&&xmlhttp.status==200){
			document.getElementById("ServerInfo").innerHTML=xmlhttp.responseText;
		}	
	}
	//alert(str);
	xmlhttp.open("GET","view/ajax/checkUserName.jsp?username="+str,true);
	xmlhttp.send();
}

jsp页面<%%>中加入以下代码
Class.forName("com.mysql.jdbc.Driver");   
    Connection conn=DriverManager.getConnection   
            ("jdbc:mysql://localhost:3306/credit","root","admin");   
    Statement stmt=conn.createStatement();
    //request字符编码
    //out.println(request.getCharacterEncoding());
    String uname=request.getParameter("username");
    //JAVA在网络传输中使用的编码是"ISO-8859-1",经过网络编码后的中文,要正确显示在页面上必须要用类似于
    String str=new String(uname.getBytes("ISO-8859-1"),"GBK");
    //out.println(str);
    ResultSet rs=stmt.executeQuery("select userid from user where username='"+str+"'");
    rs.last();
    //int length = rs.getRow(); 
    //out.println(length);
    if(rs.getRow()==0){
    	out.println("<font color="+"green"+" size="+"-1"+">");
    	out.println("用户名可用!");
    	out.println("</font>");
    }else{
    	out.println("<font color="+"red"+" size="+"-1"+">");
    	out.println("用户名已存在!");
    	out.println("</font>");
    }