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

ajax jquery校验用户是否已经注册

服务端代码这里就不贴了

html代码比较简单,需要自行引入jquery库

<body>
		请输入用户名:<input type="text" id="userName" class="userText"/> <input type="button" value="校验" id="verifyButton" />
		<div id="result"></div>
	</body>

js代码

/*
 * 在页面装载完成时注册上这些工作
 * */
$(document).ready(function() {
	//这里面的内容就是页面装载完成后需要执行的代码
	var userNameNode = $("#userName");	
	//需要找到button按扭,注册事件
	$("#verifyButton").click(function() {
		//1.获取文本框的内容
		var userName = userNameNode.val();
		//2.将这个内容发送给服务器端
		if (userName == "") {
			alert("用户名不能为空");
		} else {
			$.get("http://127.0.0.1:8080/JQuery/UserVerify?userName=" + encodeURI(encodeURI(userName)),null,function(response){
					//3.接收服务器端返回的数据,填充到div中	
					$("#result").html(response);
				});		
			
		}
	});
	//需要找到文本框,注册事件
	userNameNode.keyup(function(){
		//获取当前文本框中的内容
		var value = userNameNode.val();
		if (value == "") {
			//让边框变成红色,并且带背景图
			userNameNode.addClass("userText");
		} else {
			//去掉边框和背景图
			userNameNode.removeClass("userText");
			
		}
	});
});

css样式,目的是让文本框中没有内容的时候边框为红色并下方有红色波浪

.userText {
    /*控制文本框的边框是红色的实线*/
    border: 1px solid red;
    background-image: url(../images/userVerify.gif);
    background-repeat: repeat-x;
    background-position: bottom;
}